【本文原创,转载请注明出处】
实际效果:
实现思路:
结合 RecyclerView 实现,横向可拖动 Tab 导航栏。
使用方法:
第一步:一些成员变量:private RecyclerView mHorizontalSpeciesRecycler;
private TextView tv[] = new TextView[10];//用于记录选择了哪个种类商品 灰色变红色
private int i = 0;
private String index = "name0";//用于标记tv
第二步:创建 RecyclerView :public void setmHorizontalSpeciesListView() {
Listdata = initHorizontalSpeciesData();
mHorizontalSpeciesRecycler = (RecyclerView) goodsView.findViewById(R.id.main_goods_page_horizontal_species_list);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity());
((LinearLayoutManager) manager).setOrientation(LinearLayoutManager.HORIZONTAL);
mHorizontalSpeciesRecycler.setLayoutManager(manager);
mHorizontalSpeciesRecycler.setAdapter(new HorizontalSpeciesListAdapter(data));
}
第三步:为 RecyclerView 配置 Adapter :class HorizontalSpeciesListAdapter extends RecyclerView.Adapter{
//② 创建ViewHolder
class VH extends RecyclerView.ViewHolder{
private final TextView name,selectedBar;
public VH(View v) {
super(v);
v.getLayoutParams().width = getActivity().getWindowManager().getDefaultDisplay().getWidth() / 4 + 30;
v.getLayoutParams().height = v.getLayoutParams().width / 2 ;
name = (TextView) v.findViewById(R.id.main_goods_species_name);
tv[i++] = selectedBar = (TextView) v.findViewById(R.id.main_goods_selected_bar);
}
}
private ListmDatas;
public HorizontalSpeciesListAdapter(Listdata) {
this.mDatas = data;
}
//③ 在Adapter中实现3个方法
@Override
public void onBindViewHolder(final HorizontalSpeciesListAdapter.VH holder, int position) {
holder.name.setText(mDatas.get(position).getSpeciseName());
if (mDatas.get(position).getSpeciseName().equals(index)){
holder.selectedBar.setBackgroundColor(Color.RED);
}else {
holder.selectedBar.setBackgroundColor(Color.GRAY);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//item 点击事件
try {
for (TextView j:tv){
j.setBackgroundColor(Color.GRAY);
}
}catch (Exception e){
}
holder.selectedBar.setBackgroundColor(Color.RED);
index = holder.name.getText().toString();
Toast.makeText(getActivity(),"click",Toast.LENGTH_SHORT).show();
}
});
}
@Override
public int getItemCount() {
return mDatas.size();
}
@Override
public HorizontalSpeciesListAdapter.VH onCreateViewHolder(ViewGroup parent, int viewType) {
//LayoutInflater.from指定写法
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.main_goods_horizontal_species_list, parent, false);
return new HorizontalSpeciesListAdapter.VH(v);
}
}
第四步:为 RecyclerView 添加测试信息:private ListinitHorizontalSpeciesData(){
ListmainHorizontalList = new ArrayList<>();
for (int i = 0 ; i < 10 ; i++){
mainHorizontalList.add(new GoodsSpecies("name" + i));
}
return mainHorizontalList;
}
【因为是在写项目中想到的,所以如果哪里有疑问,请在评论区留言。】
如果本文对您有帮助,欢迎关注我获得更多信息。