使用ViewPager和Fragment同时实现点击底部Tab切换和手势滑动切换Fragment

使用ViewPager和Fragment实现页面切换,点击Tab切换Fragment,手势滑动切换Fragment,那现在就一步步的来实现。

先进行XML布局

<RelativeLayout 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"
    tools:context=".MainActivity" >

<!-- 底部四个导航按钮 -->
<LinearLayout
    android:id="@+id/ll_tabs"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal"
    >


    <LinearLayout
        android:id="@+id/lin_one"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:layout_gravity="center_horizontal"
        android:background="#ffffff"
       >
        <ImageView
            android:layout_width="30dp"
            android:src="@mipmap/main_switch"
            android:layout_gravity="center_horizontal"
            android:layout_height="30dp" />
        <TextView
            android:id="@+id/tv_main"
            android:layout_width="match_parent"
            android:text="首页"
            android:gravity="center_horizontal"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/lin_two"
        android:layout_width="0dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#ffffff"
        >
        <ImageView
            android:layout_width="30dp"
            android:src="@mipmap/my_switch"
            android:layout_gravity="center_horizontal"
            android:layout_height="30dp" />
        <TextView
            android:id="@+id/tv_contact"
            android:layout_width="match_parent"
            android:text="联系人"
            android:gravity="center_horizontal"
            android:layout_height="wrap_content" />
    </LinearLayout>
    <LinearLayout
        android:id="@+id/lin_three"
        android:layout_width="0dp"
        android:orientation="vertical"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#ffffff"
        >

        <ImageView
            android:layout_width="30dp"
            android:src="@mipmap/my_switch"
            android:layout_gravity="center_horizontal"
            android:layout_height="30dp" />
        <TextView
            android:id="@+id/tv_my"
            android:layout_width="match_parent"
            android:text="我的"
            android:gravity="center_horizontal"
            android:layout_height="wrap_content" />

    </LinearLayout>
    <LinearLayout
        android:id="@+id/lin_four"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:orientation="vertical"
        android:background="#ffffff"
        >
        <ImageView
            android:layout_width="30dp"
            android:src="@mipmap/main_switch"
            android:layout_gravity="center_horizontal"
            android:layout_height="30dp" />
        <TextView
            android:id="@+id/tv_set"
            android:layout_width="match_parent"
            android:text="设置"
            android:gravity="center_horizontal"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>

<!-- 导航和视图的分割线 -->
<View
    android:layout_width="match_parent"
    android:layout_height="2dp"
    android:background="#0eefff"
    android:layout_above="@id/ll_tabs"
    />

<!--
<RelativeLayout
    android:id="@+id/fragment_content_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/ll_tabs"
    android:layout_marginBottom="2dp"
    android:background="#fff"
    />
 -->
<!-- VIewPager 主要是加载内容的 -->
<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    android:layout_above="@id/ll_tabs"
    android:layout_marginBottom="2dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
</RelativeLayout>

主活动中代码的编写(详情看注释)

package com.cca.an.myfragment;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

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

public class MainActivity extends FragmentActivity implements OnClickListener{

/**
 * 四个导航
 */
LinearLayout lintonOne;
LinearLayout lintonTwo;
LinearLayout lintonThree;
LinearLayout lintonFour;

/**
 * 作为页面容器的ViewPager
 */
ViewPager mViewPager;
/**
 * 页面集合
 */
List<Fragment> fragmentList;

/**
 * 四个Fragment(页面)
 */
ChatFragment oneFragment;
ContactFragment twoFragment;
MyFragment threeFragment;
SetFragment fourFragment;

//屏幕宽度
int screenWidth;
//当前选中的项
int currenttab=-1;
private TextView tvmain;
private TextView tvcontact;
private TextView tvmy;
private TextView tvset;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(R.layout.activity_main);
    lintonOne= (LinearLayout) findViewById(R.id.lin_one);
    lintonTwo=(LinearLayout) findViewById(R.id.lin_two);
    lintonThree=(LinearLayout) findViewById(R.id.lin_three);
    lintonFour=(LinearLayout) findViewById(R.id.lin_four);


    tvmain = (TextView) findViewById(R.id.tv_main);
    tvcontact = (TextView) findViewById(R.id.tv_contact);
    tvmy = (TextView) findViewById(R.id.tv_my);
    tvset = (TextView) findViewById(R.id.tv_set);


    lintonOne.setOnClickListener(this);
    lintonTwo.setOnClickListener(this);
    lintonThree.setOnClickListener(this);
    lintonFour.setOnClickListener(this);

    mViewPager=(ViewPager) findViewById(R.id.viewpager);

    fragmentList=new ArrayList<Fragment>();
    oneFragment=new ChatFragment();
    twoFragment=new ContactFragment();
    threeFragment=new MyFragment();
    fourFragment=new SetFragment();

    fragmentList.add(oneFragment);
    fragmentList.add(twoFragment);
    fragmentList.add(threeFragment);
    fragmentList.add(fourFragment);

    mViewPager.setAdapter(new MyFrageStatePagerAdapter(getSupportFragmentManager()));

    tvmain.setTextColor(Color.RED);
}


/**
 * 定义自己的ViewPager适配器。
 * 也可以使用FragmentPagerAdapter。关于这两者之间的区别,可以自己去搜一下。
 */
class MyFrageStatePagerAdapter extends FragmentStatePagerAdapter
{

    public MyFrageStatePagerAdapter(FragmentManager fm)
    {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

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

    /**
     * 每次更新完成ViewPager的内容后,调用该接口,此处复写主要是为了让导航按钮上层的覆盖层能够动态的移动
     */
    @Override
    public void finishUpdate(ViewGroup container)
    {
        super.finishUpdate(container);//这句话要放在最前面,否则会报错
        //获取当前的视图是位于ViewGroup的第几个位置,用来更新对应的覆盖层所在的位置
        int currentItem=mViewPager.getCurrentItem();
        if (currentItem==currenttab)
        {
            return ;
        }
    //    imageMove(mViewPager.getCurrentItem());
        currenttab=mViewPager.getCurrentItem();
        if (currenttab==0){
            tvmain.setTextColor(Color.RED);
        }else{
            tvmain.setTextColor(Color.BLACK);
        }
        if (currenttab==1){
            tvcontact.setTextColor(Color.RED);
        }else{
            tvcontact.setTextColor(Color.BLACK);
        }
        if (currenttab==2){
            tvmy.setTextColor(Color.RED);
        }else{
            tvmy.setTextColor(Color.BLACK);
        }
        if (currenttab==3){
            tvset.setTextColor(Color.RED);
        }else{
            tvset.setTextColor(Color.BLACK);
        }
    }

}



@Override
public void onClick(View v)
{
    switch (v.getId())
    {
        case R.id.lin_one:
            changeView(0);
            break;
        case R.id.lin_two:
            changeView(1);
            break;
        case R.id.lin_three:
            changeView(2);
            break;
        case R.id.lin_four:
            changeView(3);
            break;
        default:
            break;
    }
}
//手动设置ViewPager要显示的视图
private void changeView(int desTab)
{
    mViewPager.setCurrentItem(desTab, true);
}

}

四个页卡的简单实例,四个一样的写法

package com.cca.an.myfragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by an on 2016/10/14.
 */
public class ChatFragment extends Fragment {

    private static final String TAG = "ChatFragment";
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        Log.i(TAG, "------:Chat ");

        return  inflater.inflate(R.layout.fragment_chat,container,false);

    }
}
页卡xml文件的书写(示例)
<?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">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="这是聊天页卡"
        android:textColor="@color/colorAccent"
        android:textSize="20sp"
        android:gravity="center"/>
</LinearLayout>
至此,已经实现了页卡点击、滑动切换Fragment的功能。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是实现步骤: 1. 首先在布局文件中添加TabLayout和ViewPager2控件,如下所示: ```xml <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabGravity="fill" app:tabMode="fixed"/> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="match_parent"/> ``` 2. 在java文件中实例化TabLayout和ViewPager2控件,并设置ViewPager2的适配器,如下所示: ```java TabLayout tabLayout = findViewById(R.id.tab_layout); ViewPager2 viewPager = findViewById(R.id.view_pager); // 设置ViewPager2的适配器 viewPager.setAdapter(new MyFragmentPagerAdapter(this)); ``` 3. 创建FragmentPagerAdapter类,并实现getItemCount()和createFragment()方法,如下所示: ```java public class MyFragmentPagerAdapter extends FragmentPagerAdapter { private Context mContext; public MyFragmentPagerAdapter(Context context) { super(context); mContext = context; } @NonNull @Override public Fragment getItem(int position) { // 根据位置返回不同的Fragment switch (position) { case 0: return new Fragment1(); case 1: return new Fragment2(); case 2: return new Fragment3(); default: return new Fragment1(); } } @Override public int getItemCount() { return 3; // 返回Fragment的数量 } } ``` 4. 在java文件中为TabLayout添加Tab选项,并设置TabLayout的监听器,如下所示: ```java // 添加Tab选项 tabLayout.addTab(tabLayout.newTab().setText("Tab1")); tabLayout.addTab(tabLayout.newTab().setText("Tab2")); tabLayout.addTab(tabLayout.newTab().setText("Tab3")); // 设置TabLayout的监听器 tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { // 当Tab被选中时,切换ViewPager2对应的页面 viewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); ``` 5. 最后,在Fragment中添加自己的UI布局和逻辑代码即可。 以上就是使用TabLayout和ViewPager2实现Fragment界面切换的步骤,希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值