使用TabHost和ViewPager实现页面切换 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 技术分享 >

使用TabHost和ViewPager实现页面切换

发表时间:2020-10-19

发布人:葵宇科技

浏览次数:27


在android的开辟过程中经常会碰到页面切换的问题,个一一个解决办法是应用fragment加Handler来实现,不过有些情况下这种办法并不是最好的选择。比如,你须要滑动切换页面的时刻。这时应用TabHost和ViewPager来实现会加倍便利。文┞仿参考API文档中Creating Swipe Views with Tabs(文┞仿路径Training->Implementing Effective Navigation->Creating Swipe Views with Tabs)和west8623的文┞仿。并且参加了本身定义的标题。
代码如下:
第一步,建立mypage_layout.xml
<TabHost
        android:id="@+id/mypage_tabhost"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/mypage_r0">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TabWidget
                android:id="@android:id/tabs"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0"/>
            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="0dp"
                android:layout_height="0dip"
                android:layout_weight="0"/>
            <android.support.v4.view.ViewPager
                android:id="@+id/mypage_pager"
                android:layout_width="match_parent"
                android:layout_height="0dip"
                android:layout_weight="1"/>
        </LinearLayout>
    </TabHost>



第二步:为每个子页面建立xml,如fragment_mypage.xml;



<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/text" 
android:layout_width="match_parent" android:layout_height="match_parent" 
android:gravity="center_vertical|center_horizontal" 
android:textAppearance="?android:attr/textAppearanceMedium" 
android:text="@string/hello_world"/>

第三步:为tabHost建立自定义标签tabwidget_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#f5f5f5">
    <TextView
        android:id="@+id/tabwidget_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:text="原创"
        android:textColor="#333333"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="8dip"/>
    <View
        android:id="@+id/tabwidget_line"
        android:layout_width="match_parent"
        android:layout_height="1dip"
        android:background="#d0d0d0"
        android:layout_below="@+id/tabwidget_tv"
        android:layout_marginTop="8dip"/>
</RelativeLayout>



第四步:写主页面MyPageActivity.java,同时要建立子页面FragmentMyPager.java

public class FragmentMyPager extends Fragment
{
    int mNum;

    public static FragmentMyPager newInstance(int num)
    {
        FragmentMyPager f=new FragmentMyPager();

        Bundle args=new Bundle();
        args.putInt("num",num);
        f.setArguments(args);
        return f;
    }
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        mNum=getArguments()!=null?getArguments().getInt("num"):1;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,
                             Bundle savedInstanceState)
    {
        View v=inflater.inflate(R.layout.fragment_mypage,container,false);
        View tv=v.findViewById(R.id.text);
        ((TextView)tv).setText("Fragment # "+mNum);
        ((TextView)tv).setTextColor(getResources().getColor(R.color.black));
        return v;
    }
}
public class MyPageActivity extends FragmentActivity
{
    private TabHost mTabHost;
    private ViewPager mViewPager;
    private TabsAdapter mTabsAdapter;
    private TextView tabTv1,tabTv2;
    private View tabLine1,tabLine2,view1,view2;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mypage_layout);
        mTabHost=(TabHost)findViewById(R.id.mypage_tabhost);
        mTabHost.setup();

        mViewPager=(ViewPager)findViewById(R.id.mypage_pager);
        mTabsAdapter=new TabsAdapter(this,mTabHost,mViewPager);

        view1=(View) LayoutInflater.from(this).inflate(R.layout.tabwidget_layout,null);
        tabTv1=(TextView)view1.findViewById(R.id.tabwidget_tv);
        tabLine1=(View)view1.findViewById(R.id.tabwidget_line);

        view2=(View) LayoutInflater.from(this).inflate(R.layout.tabwidget_layout,null);
        tabTv2=(TextView)view2.findViewById(R.id.tabwidget_tv);
        tabLine2=(View)view2.findViewById(R.id.tabwidget_line);

        tabTv1.setText("原创");
        tabTv1.setTextColor(getResources().getColor(R.color.orange));
        tabLine1.setBackgroundColor(getResources().getColor(R.color.orange));

        tabTv2.setText("赞过");

        mTabsAdapter.addTab(mTabHost.newTabSpec("simple").setIndicator(view1),
                FragmentMyPager.class,null);
        mTabsAdapter.addTab(mTabHost.newTabSpec("contacts").setIndicator(view2),
                FragmentMyPager.class,null);

        if(savedInstanceState!=null)
        {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putString("tab",mTabHost.getCurrentTabTag());
    }

    private class TabInfo
    {
        private String tag;
        private Class<?> clss;
        private Bundle args;

        TabInfo(String _tag,Class<?> _class,Bundle _args)
        {
            tag=_tag;
            clss=_class;
            args=_args;
        }
    }
    private class DummyTabFactory implements TabHost.TabContentFactory
    {
        private Context mContext;

        public DummyTabFactory(Context context)
        {
            mContext=context;
        }

        @Override
        public View createTabContent(String tag)
        {
            View v=new View(mContext);
            v.setMinimumHeight(0);
            v.setMinimumWidth(0);
            return v;
        }
    }
    private class TabsAdapter extends FragmentPagerAdapter
                implements TabHost.OnTabChangeListener,ViewPager.OnPageChangeListener
    {
        private Context mContext;
        private TabHost mTabHost;
        private ViewPager mViewPager;
        private ArrayList<TabInfo> mTabs=new ArrayList<TabInfo>();

        public TabsAdapter(FragmentActivity activity,TabHost tabHost,ViewPager pager)
        {
            super(activity.getSupportFragmentManager());
            mContext=activity;
            mTabHost=tabHost;
            mViewPager=pager;
            mTabHost.setOnTabChangedListener(this);
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(TabHost.TabSpec tabSpec,Class<?> clss,Bundle args)
        {
            tabSpec.setContent(new DummyTabFactory(mContext));
            String tag=tabSpec.getTag();

            TabInfo info=new TabInfo(tag,clss,args);
            mTabs.add(info);
            mTabHost.addTab(tabSpec);
            notifyDataSetChanged();
        }

        @Override
        public int getCount()
        {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position)
        {
            TabInfo info=mTabs.get(position);
            return Fragment.instantiate(mContext,info.clss.getName(),info.args);
        }

        @Override
        public void onTabChanged(String tabId)
        {
            int position=mTabHost.getCurrentTab();
            mViewPager.setCurrentItem(position);
            if(position==0)
            {
                tabTv1.setText("原创");
                tabTv1.setTextColor(getResources().getColor(R.color.orange));
                tabLine1.setBackgroundColor(getResources().getColor(R.color.orange));

                tabTv2.setText("赞过");
                tabTv2.setTextColor(getResources().getColor(R.color.black));
                tabLine2.setBackgroundColor(getResources().getColor(R.color.linebg));
            }else if(position==1)
            {
                tabTv2.setText("赞过");
                tabTv2.setTextColor(getResources().getColor(R.color.orange));
                tabLine2.setBackgroundColor(getResources().getColor(R.color.orange));

                tabTv1.setText("原创");
                tabTv1.setTextColor(getResources().getColor(R.color.black));
                tabLine1.setBackgroundColor(getResources().getColor(R.color.linebg));
            }
//            String tmp=mTabHost.getCurrentTabTag();
//            mTabHost.getCurrentTabView().set
        }

        @Override
        public void onPageScrolled(int position,float positionOffset,int positionOffsetPixels)
        {
        }

        @Override
        public void onPageSelected(int position)
        {
            TabWidget widget=mTabHost.getTabWidget();
            int oldFocusability=widget.getDescendantFocusability();
            widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
            mTabHost.setCurrentTab(position);
            widget.setDescendantFocusability(oldFocusability);
        }
        @Override
        public void onPageScrollStateChanged(int state)
        {

        }
    }
}

相关案例查看更多