2016-12-30 29 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

    是適配器顯示? –