我的活动中有recyclerview,并将其与自定义布局绑定。我在textview上有点击监听器。当我点击textview时,我正在改变textview的颜色。
我的问题是,当我点击第一个textview时,它也会改变第13个textview的颜色。我想要多个项目选择。
这是我的代码
Recyclerview
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view_test_QNo"
android:layout_width="match_parent"
android:layout_height="58dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="7dp"
android:background="@color/unVisited" />
自定义适配器
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.viewHolder> {
private ArrayList<String> questionNo;
Context _context;
public TestAdapter(Context context, ArrayList<String> questionNo){
_context=context;
this.questionNo = questionNo;
this._callback=callback;
}
@Override
public viewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
@SuppressLint("InflateParams") View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_test,null);
return new viewHolder(view);
}
@Override
public void onBindViewHolder(final viewHolder holder, int position) {
holder.textView.setText(questionNo.get(position));
}
@Override
public int getItemCount() {
return questionNo.size();
}
class viewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView;
viewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.tv_QuesNo_custom);
textView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
textView.setTextColor(Color.RED);
}
}
}
custom_test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/tv_QuesNo_custom"
android:layout_width="42dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_marginRight="50dp"
android:gravity="center"
android:textSize="30sp"
/>
</LinearLayout>
答案 0 :(得分:0)
首先初始化 整数selectedPosition = -1;
然后在onBindViewHolder
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.textView.setText(questionNo.get(position));
holder.textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectedPosition = position;
notifyDataSetChanged();
}
});
if(selectedPosition == position){
holder.textView.setTextColor(Color.parseColor("#FF0000"));
}
else
{
//You can set your color
}
}