Android使用ViewPager+Fragment实现定制TabHost选项卡效果

Android使用ViewPager+Fragment实现定制TabHost选项卡效果

使用viewpager和fragment实现tabhost效果的步骤如下

  1. 创建Activity
  2. 创建Fragment
  3. 开始定制CustomTabHost类
  4. 在Activity中使用

效果图

Android使用ViewPager+Fragment实现定制TabHost选项卡效果_第1张图片

1、创建Activity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_mineproject);
        initViews();
    }
}

Avtivity布局文件

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

    <LinearLayout
        android:background="#fff"
        android:layout_width="fill_parent"
        android:layout_height="48dp">

        <TextView
            android:id="@+id/tv_one"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"
            android:gravity="center"
            android:text="选项卡一"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tv_two"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0"
            android:gravity="center"
            android:text="选项卡二"
            android:textColor="#000000" />

    LinearLayout>

    <TextView
        android:id="@+id/text_cursor"
        android:background="#0077c7"
        android:layout_width="40dp"
        android:layout_height="3dp" />

    <android.support.v4.view.ViewPager
        android:layout_marginTop="5dp"
        android:background="#fff"
        android:id="@+id/viewpager"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_gravity="center"
        android:layout_weight="1.0"
        android:flipInterval="30"
        android:persistentDrawingCache="animation" />

LinearLayout>

2、创建Fragment

如有多个fragment,请先各自创建好fragment

public class VicinalProjectFragment extends Fragment {
    private Context context;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_mineproject_vicinal,container,false);
        context = view.getContext();
        return view;
    }
}

Fragment布局文件


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:text="6666"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
LinearLayout>

3、实现CustomTabHost类仿制TabHost效果

/**
 * Created by jenkins on 2018/3/23.
 */

public class CustomTabHost implements View.OnClickListener,
        ViewPager.OnPageChangeListener{
    private AppCompatActivity activity;//应用上下文
    private int second =200;//滑动条动画经历的秒数
    private int screenWidth;//屏幕宽度
    private int currentIndex = 0;//当前页面
    private Map ids = new HashMap(); //配对tabview的id对应的页面
    private TextView cursor;//游标
    private ViewPager viewpager;//viewpager容器
    private ArrayList views;//标题
    private ArrayList fragments;//fragments集合

    public CustomTabHost(){}
    //构造函数
    public CustomTabHost(AppCompatActivity activity, TextView cursor,ViewPager viewPager,ArrayList views, ArrayList fragments){
        this.activity = activity;
        this.cursor = cursor;
        this.viewpager = viewPager;
        this.views = views;
        this.fragments = fragments;
        initViews();
    }

    public CustomTabHost setProcessTime(int secend){
        this.second = secend;
        return this;
    }

    public void initViews(){
        //step 1:获取屏幕宽度
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;

        //step 2:初始化滑动条的宽度,用textview作滑动条
        ViewGroup.LayoutParams params = cursor.getLayoutParams();
        params.width = screenWidth/views.size();//计算滑动条得到宽度
        cursor.setLayoutParams(params);

        //step 3 : 初始化fragmentmanager
        FragmentManager fm = activity.getSupportFragmentManager();

        //step 4: 初始化fragment适配器
        ViewPagerAdapter fragmentAdapter = new ViewPagerAdapter(fm,fragments);
        //step 5:为viewpager设置适配器
        viewpager.setAdapter(fragmentAdapter);
        viewpager.setCurrentItem(0);
        viewpager.addOnPageChangeListener(this);
        setClickListenter();
    }

    public CustomTabHost setClickListenter(){
        int length = views.size();
        if (length==0)return this;
        for(int i =0;iint id = view.getId();
            ids.put(id,i);
            view.setOnClickListener(this);
        }
        return this;
    }

    @Override
    public void onPageSelected(int target) {
        Animation animation = null;
        //计算当前页面对应的游标的x轴距离
        int currentX = screenWidth * currentIndex / views.size();
        //计算目标页面对应游标的x轴距离
        int targetX = screenWidth * target /views.size();
        animation = new TranslateAnimation(currentX, targetX, 0, 0);
        currentIndex = target;//更新当前页面
        animation.setFillAfter(true);// true表示图片停在动画结束位置
        animation.setDuration(second); //设置动画时间
        cursor.startAnimation(animation);
    }
    public CustomTabHost setCursorColor(int color){
        cursor.setBackgroundColor(color);
        return this;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

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

    }
    @Override
    public void onClick(View view) {
        //Toast.makeText(activity, "view "+ids.get(view.getId()), Toast.LENGTH_SHORT).show();
        viewpager.setCurrentItem(ids.get(view.getId()));
    }

    //ViewpagerAdapter内部类
    public class ViewPagerAdapter extends FragmentPagerAdapter {
        private FragmentManager fragmetnmanager;  //创建FragmentManager
        private ArrayList viewLists;
        public ViewPagerAdapter(FragmentManager fm, ArrayList viewLists) {
            super(fm);
            this.viewLists = viewLists;
            this.fragmetnmanager = fm;
        }
        @Override
        public int getCount() {
            return viewLists.size();
        }
        @Override
        public android.support.v4.app.Fragment getItem(int arg0) {
            return viewLists.get(arg0); //返回第几个fragment
        }
    }
}
关键函数说明
  1. initView()用于初始化TabHost的选项菜单
  2. setProcessTime()函数用于设置滑动条的滑动事件
  3. setCursorColor()函数用于设置滑动条的颜色
  4. onPageSelected()函数响应viewpager更改页面时的动作

4、在Activity中使用

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_mineproject);
        initViews();
    }

    public void initViews(){

        //step 1:初始化控件
        TextView tv_one = findViewById(R.id.tv_one);
        TextView tv_two = findViewById(R.id.tv_two);
        TextView cursor = findViewById(R.id.text_cursor);
        ViewPager viewPager = findViewById(R.id.viewpager);

        //创建tab集合
        ArrayList views = new ArrayList<>();
        views.add(tv_one);
        views.add(tv_two);
        //创建fragment集合
        ArrayList fragments = new ArrayList<>();
        fragments.add(new VicinalProjectFragment());
        fragments.add(new ReceivedInvitationFragment());

        //初始化CustomTabHost
        new CustomTabHost(this,cursor,viewPager,views,fragments)
        //参数分别为:上下文,游标,viewpager,标题集合,fragment集合
                .setProcessTime(200)                //设置滑动条的动画时间
                //或者可以填写Color.BLUE或其他颜色,也可以使用RGB颜色
    }

你可能感兴趣的:(android)