问题描述
我是Android新手,我具有带自定义适配器的ListView
,如果ListView
项目中的匹配项想要更改Activity
列表项目文本颜色,则传递一个字符串。
这是我的代码:
MyActivity:
public void handleResult(String rawResult) { if(Utility.isNotNull(rawResult.getText().toString())) { for(int i=0;i<listView.getAdapter().getCount();i++){ if(rawResult.equals(listItems.get(i).getStockItems())){ // listView.getChildAt(i).setBackgroundColor(ContextCompat.getColor(context, R.color.hint)); /* Here I want to change list item text color*/ adapter.notifyDataSetChanged(); } } } }
提前致谢!
1楼
UI任务只能在UI线程上完成。 如果要从处理程序中运行它,则必须定义一个runOnUiThread方法。 看看这个ans
2楼
试试这个代码:
for(int i=0;i<listView.getChildCount();i++) {
// yours code
View item = listView.getChildAt(i);
item.setBackgroundResource(R.drawable.your_image); //change image
((TextView)item.findViewById(R.id.text1)).setTextColor(Color.RED); //text1 is your cusotm listview item's text id
adapter.notifyDataSetChanged();?
}
3楼
我假设您使用TextView
,要更改他的文本颜色,首先需要得到他,在创建Item时,将id添加到TextView
与XML
<TextView
android:id="@+id/myId"...
或者如果您使用Java
textView.setId(R.id.myId)
并在您的代码中:
((TextView)listView.getChildAt(i).findViewById(R.id.myId)).setTextColor(ContextCompat.getColor(context, R.color.hint));
如果要使用Drawble图像设置项目背景,则可以使用.setBackground(getResources()。getDrawable(R.drawable.yourDrawble));
4楼
在模型类中添加一个这样的参数
public class DataHolder{
private String StockItems;
private int isSelected;
public DataHolder(String StockItems, int isSelected) {
this.StockItems = StockItems;
this.isSelected = isSelected;
}
public String getStockItems() {
return StockItems;
}
public void setStockItems(String StockItems) {
this.StockItems = StockItems;
}
public int getiIsSelected() {
return isSelected;
}
public void setIsSelected(String isSelected) {
this.isSelected = isSelected;
}
}
初始化IsSelected零
public void handleResult(String rawResult) {
if(Utility.isNotNull(rawResult.getText().toString())) {
for(int i=0;i<listView.getAdapter().getCount();i++){
if(rawResult.equals(listItems.get(i).getStockItems())){
listItems.get(i).setIsSelected(1);
adapter.notifyDataSetChanged();
}
}
}
}
在cusom适配器类中检查
if(listItems.get(i).getiIsSelected()==1)
{
//set red text color
}
else
{
//set black text color
}
5楼
在Adapter类中创建一个方法来更新文本颜色,并在Adapter中创建一个最初为false的标志,请使用以下方法来执行此操作
boolean isChangeColor = false;
String colorCode = "#FFFFFF";
private void updateTextColor(boolean isChangeColor , String colorCode) {
this.isChangeColor=isChangeColor;
this.colorCode=colorCode;
notifyDataSetChanged();?
}
并在getView()中
if(isChangeColor) {
textView.setTextColor(Color.parseColor(colorCode));
} else {
colorCode = "#FFFFFF";
textView.setTextColor(Color.parseColor(colorCode));
}