您的位置:首页 > 移动开发 > Android开发

Android recyclerView/listview的点击变色、点击换背景颜色

2018-01-18 14:07 1761 查看

一言不合就上图



点击变色:

这里没有用到什么高大上的技术点,只是静下心好好想想“面向对象”,利用一点小逻辑。

我这里用的是recyclerView控件,在recyclerView的适配器里:

//先声明一个int成员变量
private int thisPosition;
//再定义一个int类型的返回值方法
public int getthisPosition() {
return thisPosition;
}

//其次定义一个方法用来绑定当前参数值的方法
//此方法是在调用此适配器的地方调用的,此适配器内不会被调用到
public void setThisPosition(int thisPosition) {
this.thisPosition = thisPosition;
}
//在recyclerView的onBindViewHolder重写方法中判断当前position是否是选中的position
//如果是就设置背景,不是就设置另一种颜色的背景
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {

final RecViewHolderLeft recViewHolderLeft = (RecViewHolderLeft) holder;
if (position == getthisPosition()) {
recViewHolderLeft.titel.setBackgroundColor(Color.YELLOW);
} else {
recViewHolderLeft.titel.setBackgroundColor(Color.WHITE);
}


紧接着是在activity或者fragment的点击条目事件的地方进行调用适配器内的setThisPosition方法和点击事件的position进行绑定

RecAdapterLeft recAdapterLeft = new RecAdapterLeft(getActivity(), leftBean);
recViewL.setAdapter(recAdapterLeft);
//recyclerView的点击事件(点击事件是recyclerView专属的自定义回传接口)
//不是recyclerView的话点击事件有所不同
recAdapterLeft.setOnRecyclerViewItemClickListener(new RecAdapterLeft.OnItemClickListener() {
@Override
public void onClick(int position) {
//拿适配器调用适配器内部自定义好的setThisPosition方法(参数写点击事件的参数的position)
recAdapterLeft.setThisPosition(position);
//嫑忘记刷新适配器
recAdapterLeft.notifyDataSetChanged();
}
});


ok大功告成

强调几点:

1我的Android studio是2.3.3版本,SDK是-v7:26.+’

compile 'com.android.support:appcompat-v7:26.+'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: