2016-10-10 9 views
-2

ListViewの要素の背景色を変更する必要があります。 lvLinks.getCount()は正しい値を返します。 「If-else」とログも正しく機能します。しかし、それは動作しません(バックグラウンドの色は変わりません)。私を助けてください!私のコードを理解することを願っています。ListViewの要素の背景色を変更するには(ContentProviderのデータ)?

final Uri CONTACT_URI = Uri.parse("content://com.application.provider.LinkProvider/links"); 
ListView lvLinks; 
Cursor cursor; 
SimpleCursorAdapter adapter; 


protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.history); 

    lvLinks = (ListView) findViewById(R.id.lvLinks); 
    showListView(null); 
    setBackgroundColor(); 
    lvLinks.setOnItemClickListener(this); 
} 


public void showListView(String order){ 
    cursor = getContentResolver().query(CONTACT_URI, null, null, 
      null, order); 
    startManagingCursor(cursor); 

    int to[] = { android.R.id.text1, android.R.id.text2 }; 
    String from[] = {"ref" , "status"}; 
    adapter = new SimpleCursorAdapter(this, 
      android.R.layout.simple_list_item_2, cursor, from, to); 
    lvLinks.setAdapter(adapter); 


} 

public void setBackgroundColor(){ 


    for(int i = 0; i < lvLinks.getCount(); i++){ 
     View v = lvLinks.getAdapter().getView(i, null, null); 
     Cursor cursor = (Cursor) lvLinks.getItemAtPosition(i); 
     int status = cursor.getInt(cursor.getColumnIndexOrThrow("status")); 
     Log.d("MYTAG", String.valueOf(status)); 
     if (status == 1){ 
      v.setBackgroundColor(Color.GREEN); 
      Log.d("MYTAG", "GREEN"); 
     } else if (status == 2){ 
      v.setBackgroundColor(Color.RED); 
      Log.d("MYTAG", "RED"); 
     } else if (status == 3){ 
      v.setBackgroundColor(Color.GRAY); 
      Log.d("MYTAG", "GRAY"); 
     } 
    } 
} 

答えて

1

最初に、連絡先データをその行にバインドするときに、アダプタのビューのバックグラウンドカラーを設定する必要があります。 SimpleCursorAdapterにはこれを行うロジックがありません。 CursorAdapterを拡張し、これを処理するにはbindView()を実装する必要があります。

第2:startManagingCursor()は推奨されていません。具体的にCursorLoaderLoaderフレームワークの使用方法を学びます。

+0

ありがとう!今それは動作します。 –

関連する問題