您好我想知道如何更改ListView上所选项目的文字颜色? 我有一个ListView片段,我希望在用户点击某个项目时更改颜色文本。我在onListItemClick()函数上尝试了一些东西,但是它没有用。
你能帮我吗?
答案 0 :(得分:1)
公共类TripAdapter扩展了RecyclerView.Adapter {
private Context mContext;
private List<A> avList = new ArrayList<>();
//用于跟踪新的当前点击项位置
private int mSelectedPosition = -1;
class MyViewHolder extends RecyclerView.ViewHolder {
Button btnOpen;
TextView tvearn;
MyViewHolder(View view) {
super(view);
btnOpen = view.findViewById(R.id.btn_open);
tvearn = view.findViewById(R.id.tv_earn);
}
}
public TripAdapter(Context context, List<A> avList) {
mContext = context;
this.avList = avList;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView =LayoutInflater.from(parent.getContext()).inflate(R.layout.one_way_list_item, parent, false);
return new MyViewHolder(itemView);
}
// supopose你想要清单tvEarn textView颜色,当列表项单击,否则它设置默认;
如果单击listem,此行textview将为白色 否则设置为黑色
@Override
public void onBindViewHolder(ViewHolderInsurer holder, @SuppressLint("RecyclerView") final int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mSelectedPosition = position;
notifyDataSetChanged();
}
});
if (mSelectedPosition == position) {
holder.tvearn.setTextColor("#ffffff");
} else {
holder.radioButton.setTextColor("#000000");
}
}
@Override
public int getItemCount() {
return avList.size();
}
}
答案 1 :(得分:0)
正如您所提到的,您已经创建了android:textColor="@drawable/button_text"
。像这样制作你的button_text
<item
android:state_pressed="true"
android:color="#ff000000" />
<item
android:state_selected="true"
android:color="#ffff0000" <!-- selected color -->
/>
<item
android:state_focused="true"
android:color="#ff0000ff" />
<item android:color="#ff000000" /> <!-- default color-->
在Java代码中使用view.setSelected(true)
在onItemClick()方法中使用它。
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
view.setSelected(true);
}
});