2016-12-30 31 views
0

我有一个ListView其具有ArrayAdapter从 一个字符串数组获取信息。我试图使用一个自定义适配器类,在那里我必须重写getView()方法,其中我还使用ViewHolder模式来实现我正在尝试完成的模式。然而,这是一场噩梦,因为许多观点重复了自己,或根本没有展示,而且所有的行都是混乱的。列表视图的定制

我现在用它的适配器实现ListView的时间要短得多。 但是,我想完成的是ListView的一些行将显示红色文本和其他白色文本。将以红色显示的文本具有子字符串“R2”。请记住,此文本存储在适配器也具有句柄的字符串数组中。那么,这是我的代码,但仍然无法显示在ListView内部具有红色子字符串“R2”的文本。

ArrayAdapter<String> adapter new ArrayAdapter<String>(context, 
android.R.layout.simple_list_item_1,main_instructions); 
listview.setAdapter(adapter); 

for(int k = 0 ; k < list_layout.getChildCount(); k++){ 
String s = main_instrutions[k]; 
if(s.contains("R2")){ 
TextView v = (TextView) listview.getChildAt(k); 
s = s.replaceAll("R2",""); 
v.setTypeface(Typeface.DEFAULT_BOLD); 
v.setTextColor(Color.RED); 
v.setText(s); 
adapter.notifyDataSetChanged(); 
listview.invalidate(); 
} 

我想我有个好主意,但我无法改变这些特定的行 红色文本。如果任何人有建议,会很好。

感谢

+0

尝试在适配器中执行此操作 – Athul

+0

post ur adapter – Athul

+0

您正在调用adapter.notifyDataSetChanged();在改变视图颜色后,你应该在Adapter类中做到这一点。 – Abhijeet

回答

0

这是童话容易的,由于某种原因,我停止使用ListView的momemt RecyclerView被释放,但逻辑是神仙一样的。如果是我我首先通过与具有使一个substring创建

1. data model开始其难看和不推荐 样品模型将看起来像

public class myModel{ 

private String myString; 
private int viewColor; 

public myModel(String myString, int viewColor) 
{ 
this.myString = myString; 
this.viewColor = viewColor; 
} 
.... 
} 
  • 创建public static final int VIEW_COLOR_RED并希望所有其他颜色有
  • 当初始化模型specifiy的viewtype如list.add("this String", VIEW_COLOR_RED);
  • 在你的ListView适配器使用这种模式,你可能要到g oogle如何使用模型而不是字符串。
  • 我不确定有关listview其已久自去年我用它,但在recyclerview我们有一个方法叫onBindViewHolder() which is in charge of inflating the adapter so you look for the method in your adapter where you inflate the view and do something like

    if(myModel.getViewType == VIEW_COLOR_RED) { txt_price.setTextColor(ContextCompat.getColor(context,R.color.red); }

  • 它这么简单,好运和我强烈建议切换到RecyclerView更容易,如果你问我,因为你需要完整的代码为recyclerview和一个适配器,切换文本颜色评论下面我有代码完全是这样的。

    +0

    我没有使用电脑,从我的头写的代码,所以它可能不会在那里工作,然后 –

    +0

    我刚刚发现调用“listview.getChildCount()返回零..我不知道为什么..如果listview已经用适配器初始化了怎样才能访问这个listview的子视图? –

    +0

    是适配器显示? –