首先声明一点,写这两个View纯粹为了练习而已,要实现这个功能完全可以直接用ViewPager和TabLayout完成
下面首先给出效果图
[](
Activity、Adapter代码如下
public class MyViewPagerActivity extends Activity {
private MyViewPager mVp;
private MyTabLayout mTab;
public static final String[] mTitles = {
"视频","图片","小说","杂志","明星","体育","游戏","竞技","中医"};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_viewpager);
mVp = findViewById(R.id.vp);
mTab = findViewById(R.id.tab);
BaseAdapter adapter = new MyBaseAdapter();
mVp.setAdapter(adapter);
mTab.setViewPager(mVp);
}
class MyBaseAdapter extends BaseAdapter {
@Override
public int getItemCount() {
return mTitles.length;
}
@Override
public View getView(int position) {
return MyViewManager.getInstance().getView(getApplicationContext(), position);
}
@Override
public String getTitle(int position) {
return mTitles[position];
}
}
static class MyViewManager {
private SparseArray<View> mViews = new SparseArray<>();
public static MyViewManager getInstance() {
return MyViewManagerHolder.mViewManager;
}
public View getView(Context context, int position) {
if (mViews.get(position) != null) {
return mViews.get(position);
}
RecyclerView rv = new RecyclerView(context);
rv.setLayoutManager(new LinearLayoutManager(context));
rv.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
rv.setAdapter(new CommonAdapter(context, mTitles[position]));
mViews.put(position, rv);
return rv;
}
private static class MyViewManagerHolder {
private static MyViewManager mViewManager = new MyViewManager();
}
}
}
public class CommonAdapter extends RecyclerView.Adapter<CommonAdapter.ViewHolder> {
private List<String> mList;
private OnItemClickListener mListener;
private Context mContext;
CommonAdapter(Context context, String title) {
mList = new ArrayList<>();
mContext = context;
for (int i=0; i<100; i++) {
mList.add(title + " " + i);
}
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_main_layout, parent, false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
holder.mTv.setText(mList.get(position));
holder.mTv.setOnClickListener((v) -> {
Toast.makeText(mContext, mList.get(position), Toast.LENGTH_SHORT).show();
});
holder.itemView.setOnClickListener((view) -> {
if (mListener != null) {
mListener.onItemClick(view, holder.getLayoutPosition());
}
});
holder.itemView.setOnLongClickListener((view) -> {
if (mListener != null) {
mListener.onItemLongClick(view, holder.getLayoutPosition());
}