FragmentPagerAdapter+ViewPager实现Tab

转载请注明出处amoscxy的博客:https://mp.csdn.net/mdeditor/80158316

转载请注明出处amoscxy的博客:https://mp.csdn.net/mdeditor/80158316

FragmentPagerAdapter+ViewPager实现Tab

1.1 效果

这里写图片描述

1.2 目录

这里写图片描述

1.3 素材

  • bottom_bar9.png
    这里写图片描述
    • tab_address_normal.png
      这里写图片描述
    • tab_address_pressed.png
      这里写图片描述
    • tab_bg2.png
      这里写图片描述
  • tab_find_frd_normal.png
    这里写图片描述
  • tab_find_frd_pressed.png
    这里写图片描述
  • tab_settings_normal.png
    这里写图片描述
  • tab_settings_pressed.png
    这里写图片描述
  • tab_weixin_normal.png
    这里写图片描述
  • tab_weixin_pressed.png
    这里写图片描述
  • title_bar9.png
    这里写图片描述

1.4 顶部提示栏top.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:background="@drawable/title_bar9"
    android:gravity="center"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="微信"
        android:textColor="#ffffff"
        android:textSize="20sp"
        android:textStyle="bold" />

</LinearLayout>
  • 视图:
    这里写图片描述

1.5 底部标签bottom.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:background="@drawable/bottom_bar9"
    android:orientation="horizontal" >

    <LinearLayout
        android:id="@+id/id_tab_weixin"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/id_tab_weixin_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:clickable="false"
            android:src="@drawable/tab_weixin_pressed" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="微信"
            android:textColor="#ffffff" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/id_tab_frd"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/id_tab_frd_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:clickable="false"
            android:src="@drawable/tab_find_frd_normal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="朋友"
            android:textColor="#ffffff" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/id_tab_address"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/id_tab_address_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:clickable="false"
            android:src="@drawable/tab_address_normal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="通讯录"
            android:textColor="#ffffff" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/id_tab_settings"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:gravity="center"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/id_tab_settings_img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#00000000"
            android:clickable="false"
            android:src="@drawable/tab_settings_normal" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="设置"
            android:textColor="#ffffff" />
    </LinearLayout>

</LinearLayout>
  • 视图:
    这里写图片描述

1.6 activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include layout="@layout/top" />

    <android.support.v4.view.ViewPager
        android:id="@+id/id_viewpager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <include layout="@layout/bottom" />

</LinearLayout>
  • 视图:
    这里写图片描述

1.7 四个切换界面

1.7.1 tab01.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="This is Weixin Tab"
        android:textSize="30sp"
        android:textStyle="bold" />

</LinearLayout>
  • 图示:
    这里写图片描述

1.7.2 tab02.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="This is Frd Tab"
        android:textSize="30sp"
        android:textStyle="bold" />

</LinearLayout>
  • 图示:
    这里写图片描述

1.7.3 tab03.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="This is Address Tab"
        android:textSize="30sp"
        android:textStyle="bold" />

</LinearLayout>
  • 图示:
    这里写图片描述

1.7.4 tab04.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="This is Settings Tab"
        android:textSize="30sp"
        android:textStyle="bold" />

</LinearLayout>
  • 图示:
    这里写图片描述

1.8 四个自定义Fragment

1.8.1 WeixinFragment

public class WeixinFragment extends Fragment {


    public WeixinFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab01,container,false);
    }

}

1.8.2 FrdFragment

public class FrdFragment extends Fragment {


    public FrdFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab02,container,false);
    }

}

1.8.3 AddressFragment

public class AddressFragment extends Fragment {


    public AddressFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab03,container,false);
    }

}

1.8.4 SettingFragment

public class SettingFragment extends Fragment {


    public SettingFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.tab04,container,false);
    }

}

1.9 MainActivity

package com.example.cxy.testtap;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity implements OnClickListener
{
    private ViewPager mViewPager;
    private FragmentPagerAdapter mAdapter;
    private List<Fragment> mFragments;

    private LinearLayout mTabWeixin;
    private LinearLayout mTabFrd;
    private LinearLayout mTabAddress;
    private LinearLayout mTabSetting;

    private ImageButton mWeixinImg;
    private ImageButton mFrdImg;
    private ImageButton mAddressImg;
    private ImageButton mSettingImg;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        initView();
        initEvents();
        setSelect(0);
    }

    private void setSelect(int i) {
        setTab(i);
        mViewPager.setCurrentItem(i);
    }

    private void setTab(int i) {
        resetImg();
        switch(i){
            case 0:
                mWeixinImg.setImageResource(R.drawable.tab_weixin_pressed);
                break;
            case 1:
                mFrdImg.setImageResource(R.drawable.tab_find_frd_pressed);
                break;
            case 2:
                mAddressImg.setImageResource(R.drawable.tab_address_pressed);
                break;
            case 3:
                mSettingImg.setImageResource(R.drawable.tab_settings_pressed);
                break;
            default:
                break;
        }
    }

    private void initEvents()
    {
        mTabWeixin.setOnClickListener(this);
        mTabFrd.setOnClickListener(this);
        mTabAddress.setOnClickListener(this);
        mTabSetting.setOnClickListener(this);
    }

    private void initView()
    {
        mViewPager = findViewById(R.id.id_viewpager);
        // tabs
        mTabWeixin = findViewById(R.id.id_tab_weixin);
        mTabFrd = findViewById(R.id.id_tab_frd);
        mTabAddress = findViewById(R.id.id_tab_address);
        mTabSetting = findViewById(R.id.id_tab_settings);
        // ImageButton
        mWeixinImg = findViewById(R.id.id_tab_weixin_img);
        mFrdImg = findViewById(R.id.id_tab_frd_img);
        mAddressImg = findViewById(R.id.id_tab_address_img);
        mSettingImg = findViewById(R.id.id_tab_settings_img);

        mFragments = new ArrayList<Fragment>();
        Fragment mTab1 = new WeixinFragment();
        Fragment mTab2 = new FrdFragment();
        Fragment mTab3 = new AddressFragment();
        Fragment mTab4 = new SettingFragment();
        mFragments.add(mTab1);
        mFragments.add(mTab2);
        mFragments.add(mTab3);
        mFragments.add(mTab4);
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragments.get(position);
            }

            @Override
            public int getCount() {
                return mFragments.size();
            }
        };
        mViewPager.setAdapter(mAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                int currentItem = mViewPager.getCurrentItem();
                setTab(currentItem);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 底部四个ImageButton都置为normal
     */
    private void resetImg()
    {
        mWeixinImg.setImageResource(R.drawable.tab_weixin_normal);
        mFrdImg.setImageResource(R.drawable.tab_find_frd_normal);
        mAddressImg.setImageResource(R.drawable.tab_address_normal);
        mSettingImg.setImageResource(R.drawable.tab_settings_normal);
    }

    @Override
    public void onClick(View v) {
        resetImg();
        switch (v.getId()){
            case R.id.id_tab_weixin:
                setSelect(0);
                break;
            case R.id.id_tab_frd:
                setSelect(1);
                break;
            case R.id.id_tab_address:
                setSelect(2);
                break;
            case R.id.id_tab_settings:
                setSelect(3);
                break;
            default:
                break;
        }
    }
}
  • 源码分析
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

为了保持兼容性全部时候v4下的Fragment

private ViewPager mViewPager;
private FragmentPagerAdapter mAdapter;
private List<Fragment> mFragments;

private LinearLayout mTabWeixin;
private LinearLayout mTabFrd;
private LinearLayout mTabAddress;
private LinearLayout mTabSetting;

private ImageButton mWeixinImg;
private ImageButton mFrdImg;
private ImageButton mAddressImg;
private ImageButton mSettingImg;

private ViewPager mViewPager;
mViewPager是ViewPager

private FragmentPagerAdapter mAdapter;
使用FragmentPagerAdapter

private List mFragments;
用于存放4个自定义Fragment

private LinearLayout mTabWeixin;
private LinearLayout mTabFrd;
private LinearLayout mTabAddress;
private LinearLayout mTabSetting;
底部四个tabs是LinearLayout控件

private ImageButton mWeixinImg;
private ImageButton mFrdImg;
private ImageButton mAddressImg;
private ImageButton mSettingImg;
底部四个tabs中的四个ImageButton

mViewPager = findViewById(R.id.id_viewpager);
// tabs
mTabWeixin = findViewById(R.id.id_tab_weixin);
mTabFrd = findViewById(R.id.id_tab_frd);
mTabAddress = findViewById(R.id.id_tab_address);
mTabSetting = findViewById(R.id.id_tab_settings);
// ImageButton
mWeixinImg = findViewById(R.id.id_tab_weixin_img);
mFrdImg = findViewById(R.id.id_tab_frd_img);
mAddressImg = findViewById(R.id.id_tab_address_img);
mSettingImg = findViewById(R.id.id_tab_settings_img);

mFragments = new ArrayList<Fragment>();
Fragment mTab1 = new WeixinFragment();
Fragment mTab2 = new FrdFragment();
Fragment mTab3 = new AddressFragment();
Fragment mTab4 = new SettingFragment();
mFragments.add(mTab1);
mFragments.add(mTab2);
mFragments.add(mTab3);
mFragments.add(mTab4);
mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }
};
mViewPager.setAdapter(mAdapter);

是ViewPager的一般步骤,可以参考
https://blog.csdn.net/amoscxy/article/details/80153088

mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        int currentItem = mViewPager.getCurrentItem();
        setTab(currentItem);
    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
});

作用是随着ViewPager的滑动,底部tabs也跟随变动

private void setTab(int i) {
    resetImg();
    switch(i){
        case 0:
            mWeixinImg.setImageResource(R.drawable.tab_weixin_pressed);
            break;
        case 1:
            mFrdImg.setImageResource(R.drawable.tab_find_frd_pressed);
            break;
        case 2:
            mAddressImg.setImageResource(R.drawable.tab_address_pressed);
            break;
        case 3:
            mSettingImg.setImageResource(R.drawable.tab_settings_pressed);
            break;
        default:
            break;
    }
}

根据位置i,设置对应的ImageButton设置为pressed

private void resetImg()
{
    mWeixinImg.setImageResource(R.drawable.tab_weixin_normal);
    mFrdImg.setImageResource(R.drawable.tab_find_frd_normal);
    mAddressImg.setImageResource(R.drawable.tab_address_normal);
    mSettingImg.setImageResource(R.drawable.tab_settings_normal);
}

底部四个ImageButton都置为normal

private void setSelect(int i) {
    setTab(i);
    mViewPager.setCurrentItem(i);
}

根据点击的底部四个tabs,设置点击的ImageButton为pressed,设置展示的对应ViewPager

1.10 FragmentPagerAdapter+ViewPager组合的好处

  • 使用Fragment的好处是,可以通过各自的Fragment来控制自己的布局和逻辑,不会是代码都冗余在activity里面,activity只作为一个调度器,来显示和隐藏对应的Fragment,这样便于后期的维护和复用
  • 如果想让显示界面可以左右滑动最好使用FragmentPagerAdapter+ViewPager组合

转载请注明出处amoscxy的博客:https://mp.csdn.net/mdeditor/80158316

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android TableLayout is a ViewGroup which displays the data in a tabular form. It is used to create a user interface with rows and columns similar to a spreadsheet. ViewPager is a View which allows the user to swipe left and right to navigate between pages. Fragments are reusable components which can be used to create dynamic user interfaces. To create a TableLayout with ViewPager and Fragment, follow the below steps: 1. Create a new Android Studio project. 2. Add the required dependencies in the build.gradle file. 3. Create a new Fragment class for each tab. 4. Create a layout file for each Fragment. 5. Create a new FragmentPagerAdapter class to manage the Fragments. 6. Create a layout file for the Activity which will contain the TableLayout and ViewPager. 7. Add the TableLayout and ViewPager to the layout file. 8. Initialize the ViewPager in the Activity and set the FragmentPagerAdapter. 9. Create a new TabLayout and add it to the layout file. 10. Add the TabLayout to the ViewPager. Example code: 1. Add the dependencies in the build.gradle file: ``` dependencies { implementation 'com.google.android.material:material:1.4.0' implementation 'androidx.viewpager2:viewpager2:1.0.0' } ``` 2. Create a new Fragment class for each tab: ``` public class TabFragment extends Fragment { private int tabPosition; public TabFragment(int tabPosition) { this.tabPosition = tabPosition; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_tab, container, false); TextView textView = view.findViewById(R.id.tab_text); textView.setText(getString(R.string.tab_text, tabPosition + 1)); return view; } } ``` 3. Create a layout file for each Fragment: ``` <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:id="@+id/tab_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:textAppearanceLarge" /> </LinearLayout> ``` 4. Create a new FragmentPagerAdapter class to manage the Fragments: ``` public class TabAdapter extends FragmentStateAdapter { public TabAdapter(FragmentActivity activity) { super(activity); } @Override public Fragment createFragment(int position) { return new TabFragment(position); } @Override public int getItemCount() { return 3; } } ``` 5. Create a layout file for the Activity which will contain the TableLayout and ViewPager: ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content"/> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> </LinearLayout> ``` 6. Initialize the ViewPager in the Activity and set the FragmentPagerAdapter: ``` public class MainActivity extends AppCompatActivity { private ViewPager2 viewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TabLayout tabLayout = findViewById(R.id.tab_layout); viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(new TabAdapter(this)); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText("Tab " + (position + 1)) ).attach(); } } ``` 7. Create a new TabLayout and add it to the layout file: ``` <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content"/> ``` 8. Add the TabLayout to the ViewPager: ``` TabLayout tabLayout = findViewById(R.id.tab_layout); viewPager.setAdapter(new TabAdapter(this)); new TabLayoutMediator(tabLayout, viewPager, (tab, position) -> tab.setText("Tab " + (position + 1)) ).attach(); ``` This will create a TableLayout with ViewPager and Fragment. The user can swipe left and right to navigate between tabs. Each tab will display a Fragment with a TextView showing the tab number.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值