美文网首页UI 效果Android知识Android
利用FragmentTabHost和ViewPager实现类微信

利用FragmentTabHost和ViewPager实现类微信

作者: AmatorLee | 来源:发表于2016-08-04 14:03 被阅读843次

    生活本来就不容易,而我们的不努力只会让生活变得更加无赖

    今天学习了如何利用FragmentTabHost以及ViewPager的知识点,简单写了个demo实现界面滑动点击切换的效果.现在市面上大部分的APP都有这种类似的功能,如微信,简书等等,相信实现方法略同.因此便写一篇日记记录该功能的实现.demo部分截图如下:

    demo截图

    FragmentTabHost的用法(要点)

    1. Activity必须继承自FragmentActivity(AppCompatActivity为其子类).
    2. 使用setup()方法绑定Fragmenrt,
    3. 使用TabHost.TabSpec 设置spec,spec则需要indicator,indicator则需要View填充.
    4. 实现setOnTabChangedListener接口来对Viewpager的滑动进行监听

    ViewPager的用法(要点)

    1.Viewpager被添加在v4包当中,官方推荐结合Fragment使用以实现滑动切换的效果,因此需要一个适配器Adapter继承FragmentPagerAdapter装载Fragment.
    2.实现addOnPageChangeListener接口来对FragmentTabHost的点击的监听.

    由上可知,我们需要写几个xml文件显示相关::

    • tabhost.xml
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v4.view.ViewPager
            android:layout_weight="1"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:id="@+id/view_pager">
        </android.support.v4.view.ViewPager>
        <android.support.v4.app.FragmentTabHost
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@android:id/tabhost"
            android:background="@android:color/white"
            android:layout_marginTop="2dp"
            android:layout_marginBottom="2dp">
            <FrameLayout
                android:layout_width="0dp"
                android:id="@android:id/tabcontent"
                android:layout_height="0dp"
                android:layout_weight="0">
            </FrameLayout>
        </android.support.v4.app.FragmentTabHost>
    </LinearLayout>```
     * 这里需要注意的地方是,在FragmentTabHost里面的FrameLayout的id必须为```@android:id/tabcontent```
    
    * 给indicator填充的item_view.xml
    

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp">
    <ImageView
    android:id="@+id/imageview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:padding="3dp">
    </ImageView>
    <TextView
    android:id="@+id/tabtextview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="10sp"
    android:layout_gravity="center"
    android:textColor="@color/tab_text">
    </TextView>
    </LinearLayout>```

    • fragment1.xml(这里需要四个,但全部相同,先贴出一个)
    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" 
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="这是第一个Fragment"
            android:id="@+id/textView" />
    </LinearLayout>```
    
    #### ViewPager的适配器以及监听接口的实现:
    * MyAdapter.java
    

    public class MyAdapter extends FragmentPagerAdapter{
    private List<Fragment> views;
    public MyAdapter(FragmentManager fm,List<Fragment> list) {
    super(fm);
    this.views = list;
    }
    @Override
    public Fragment getItem(int position) {
    return views.get(position);
    }

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

    }```

    • MyPageChangeListener.java
    public class MyPageChangeListener implements ViewPager.OnPageChangeListener {
        private FragmentTabHost tabHost;
    
        public MyPageChangeListener(FragmentTabHost tabHost) {
            this.tabHost = tabHost;
        }
    
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
        }
    
        @Override
        public void onPageSelected(int position) {
            //界面被选择时调用
            tabHost.setCurrentTab(position);
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
    
        }
    }```
    #### Fragment(相同只贴一个)
    * Fragment1.java
    

    public class Fragment1 extends Fragment{
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment1,null);
    }
    }```

    • 注意Fragment必须继承自v4包的.

    因有多个资源需配置,所以进行简单的封装

    • Tab.java
    public class Tab {
        //标题资源
        private int title;
        //图片字图案
        private int img;
        //Fragment类资源
        private Class Fragment;
    
        public Tab(int title, int img, Class fragment) {
            this.title = title;
            this.img = img;
            Fragment = fragment;
        }
    
        public int getTitle() {
            return title;
        }
    
        public void setTitle(int title) {
            this.title = title;
        }
    
        public int getImg() {
            return img;
        }
    
        public void setImg(int img) {
            this.img = img;
        }
    
        public Class getFragment() {
            return Fragment;
        }
    
        public void setFragment(Class fragment) {
            Fragment = fragment;
        }
    }```
    
    #### MainActivity.java
    

    import android.os.Bundle;
    import android.support.annotation.Nullable;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTabHost;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.TabHost;
    import android.widget.TextView;
    import java.util.ArrayList;
    import java.util.List;

    public class TabHost_Aty extends AppCompatActivity {

    private FragmentTabHost tabHost;
    private View view = null;
    private LayoutInflater Inflater;
    private List<Tab> list = new ArrayList<>(4);
    private ViewPager viewPager;
    private List<Fragment> FragmentList = new ArrayList<>(4);
    
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabhost);
        Inflater = LayoutInflater.from(this);
        initTab();
    }
    //初始化资源
    private void initTab() {
        tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        //绑定Viewpager
        tabHost.setup(this,getSupportFragmentManager(),R.id.view_pager);
        //添加资源
        Tab tabmain = new Tab(R.string.main, R.drawable.btn_notifi, Fragment1.class);
        Tab tabcontact = new Tab(R.string.contact, R.drawable.btn_contact, Fragment2.class);
        Tab tabmine = new Tab(R.string.setting, R.drawable.btn_mine, Fragment3.class);
        Tab tabfound = new Tab(R.string.find, R.drawable.btn_found, Fragment4.class);
        list.add(tabmain);
        list.add(tabcontact);
        list.add(tabmine);
        list.add(tabfound);
    
        for (Tab tab : list) {
            TabHost.TabSpec spec= tabHost.newTabSpec(getString(tab.getTitle()))//
            .setIndicator(getItemView(tab));
            tabHost.addTab(spec,tab.getFragment(),null);
        }
        //清除分界线
        tabHost.getTabWidget().setShowDividers(LinearLayout.SHOW_DIVIDER_NONE);
        
        initFragment();
    }
    
    /**
     * 初始化ViewPager
     */
    private void initFragment() {
        FragmentList.add(new Fragment1());
        FragmentList.add(new Fragment2());
        FragmentList.add(new Fragment3());
        FragmentList.add(new Fragment4());
        viewPager = (ViewPager) findViewById(R.id.view_pager);
        //设置适配器
        viewPager.setAdapter(new MyAdapter(getSupportFragmentManager(),FragmentList));
        //设置界面滑动监听事件
        viewPager.addOnPageChangeListener(new MyPageChangeListener(tabHost));
        //设置TabHost的点击切换监听事件
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                int position  =tabHost.getCurrentTab();
                viewPager.setCurrentItem(position);
            }
        });
    }
    //给indicator配置View
    private View getItemView(Tab tab) {
        view = Inflater.inflate(R.layout.item_view, null);
    
        ImageView img = (ImageView) view.findViewById(R.id.imageview);
        TextView textview = (TextView) view.findViewById(R.id.tabtextview);
    
        img.setImageResource(tab.getImg());
        textview.setText(tab.getTitle());
    
        return view;
    }
    

    }```

    效果图:

    change.gif

    如果你觉得本文有所错漏,麻烦指出交流共同进步,谢谢!

    相关文章

      网友评论

      • a6393228bea9:作者要是能留下github地址就好了
      • 哦呀比:图片变化还有文字颜色变化怎么实现的呢
      • 喃喃南墙:有一个地方不太懂诶 请问一下有建tabhost这个布局吗...
        MainActivity.java里的onCreate方法里setContentView(R.layout.tabhost);报错了..
        厚德载物0121:R.string.mai里面字体颜色改变是怎么做的
        AmatorLee:@喃喃南墙 我重命名一下开始那个activity_main的布局文件把,不好意思,造成误解
        喃喃南墙:@喃喃南墙 明白了..

      本文标题:利用FragmentTabHost和ViewPager实现类微信

      本文链接:https://www.haomeiwen.com/subject/hsmcsttx.html