RecyclerView实现tabLayout效果(选中tab局中于屏幕)

实现方式为:RecyclerView+LinearSnapHelper(RecyclerView下的辅助类,参考:https://www.jianshu.com/p/e54db232df62

目前存在问题:

1、为了实现头尾item可以居于屏幕中间的显示效果,填充空view进行占位,因为position会有偏差。

2、子view的宽度写死的(此处偷懒),最好通过测量获取。

xml文件:

item_camera_search_or_mark.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:paddingTop="11dp"
    android:paddingBottom="11dp"
    android:text="拍照搜题"
    android:textColor="@android:color/white"
    android:textSize="14sp" />

摘取主xml里RecyclerView:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rv_search_or_mark"
    android:layout_width="match_parent"
    android:layout_height="42dp">

</androidx.recyclerview.widget.RecyclerView>

主要的RecyclerView的Adapter类:

package com.class.camera;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.didichuxing.doraemonkit.util.UIUtils;
import com.class.camera.R;

/**
 * @author hzhk
 */
public class TabCenterAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context mContext;
    /**
     * 现使用头和尾空视图占位,来达到实际意义的view可以居中于屏幕
     */
    private final int EMPTY_VIEW_COUNT=2;
    /**
     * 现使用头和尾空视图占位,来达到实际意义的view可以居中于屏幕
     */
    private final int EMPTY_VIEW_CODE = -1;
    /**
     * 填充子view的宽度
     */
    private int placeholder_width;
    /**
     * center_index当前需要高亮显示的view的位置
     */
    private int center_index = 1;
    /**
     * last_index将高亮的item恢复为默认状态时使用
     */
    private int last_index = 1;

    private RecyclerView mRecyclerView;

    private View.OnClickListener onCenterTabPositionCallBack;

    public TabCenterAdapter(Context mContext) {
        this.mContext = mContext;
        //需要注意此参数值为子view的宽度,目前是写死的宽度,后期优化通过测量获取
        placeholder_width = UIUtils.dp2px(mContext, 100);
    }

    private final String[] tabs=new String[]{"拍照搜题","拍照判卷"};

    /***
     * 设置中心
     * @param index
     */
    public void setCenter_index(int index) {
        if (index == center_index) {
            return;
        }
        last_index = center_index;
        center_index = index;
        notifyItemChanged(last_index);
        notifyItemChanged(center_index);
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType == EMPTY_VIEW_CODE) {
            View view = new View(mContext);
            int view_width = parent.getMeasuredWidth() / 2 - placeholder_width / 2;
            RecyclerView.LayoutParams params = new RecyclerView.LayoutParams(view_width, RecyclerView.LayoutParams.WRAP_CONTENT);
            view.setLayoutParams(params);
            PlaceHolderViewHolder holder = new PlaceHolderViewHolder(view);
            return holder;
        }
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_camera_search_or_mark, parent, false);
        UnionViewHolder viewHolder = new UnionViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof UnionViewHolder) {
            TextView tvBtn= (TextView) holder.itemView;
            tvBtn.setOnClickListener(onCenterTabPositionCallBack);
            tvBtn.setText(tabs[position-1]);
            if (position == center_index) {
                tvBtn.setTextColor(Color.WHITE);
            } else {
                tvBtn.setTextColor(Color.GRAY);
            }
        }
    }

    @Override
    public int getItemCount() {
        return 2+EMPTY_VIEW_COUNT;
    }

    @Override
    public int getItemViewType(int position) {
        if (position == 0 || position == getItemCount() - 1) {
            return EMPTY_VIEW_CODE;
        }
        return super.getItemViewType(position);
    }

    class UnionViewHolder extends RecyclerView.ViewHolder {

        public UnionViewHolder(View itemView) {
            super(itemView);
        }
    }

    class PlaceHolderViewHolder extends RecyclerView.ViewHolder {

        public PlaceHolderViewHolder(View itemView) {
            super(itemView);
        }
    }

    public void bindRecyclerViewScrollListener(RecyclerView recyclerView){
        mRecyclerView=recyclerView;
        final LinearSnapHelper mLinearSnapHelper = new LinearSnapHelper();
        mLinearSnapHelper.attachToRecyclerView(mRecyclerView);
        onCenterTabPositionCallBack=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //计算出SnapView需要滚动的距离
                int[] snapDistance = mLinearSnapHelper.calculateDistanceToFinalSnap(recyclerView.getLayoutManager(), v);
                mRecyclerView.smoothScrollBy(snapDistance[0],snapDistance[1]);
            }
        };
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if(newState== RecyclerView.SCROLL_STATE_IDLE){
                    RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                    if(manager instanceof LinearLayoutManager){
                        View snapView = mLinearSnapHelper.findSnapView(recyclerView.getLayoutManager());
                        int childLayoutPosition = recyclerView.getChildLayoutPosition(snapView);
                        setCenter_index(childLayoutPosition);
                    }
                }
            }
        });
    }
}

摘取Activity代码:

RecyclerView mRecyclerView=findViewById(R.id.rv_search_or_mark);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        TabCenterAdapter mUinonAdapter = new TabCenterAdapter(this);
        mRecyclerView.setAdapter(mUinonAdapter);
        mUinonAdapter.bindRecyclerViewScrollListener(mRecyclerView);
UIUtils.dp2px()方法:
public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

目前只实现了效果,可自行添加选中状态回调。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值