2017-09-06 18 views
1

私はListViewに約20の項目があります。私は第1、第3、第10の項目が黒の背景を持つようにします。私はonCreate内部ListViewで複数の項目の背景色を設定するにはどうすればよいですか?

listView.getChildAt(0).setBackgroundColor(Color.BLACK); 

を使用してみましたが、私はそれを実行したときにアプリがクラッシュしました。すべての種類をテストした後、私は結局、50ミリ秒からカウントダウンするカウントダウンタイマーを作成し、コードonFinishを実行します。しかし今、私は商品のリサイクルに問題があります。私はデフォルトに戻ってリサイクルされている項目の背景色を設定しようとしましたが、私がこれを行うと、アプリケーションがクラッシュします。 私は解決策を見回しましたが、私が見つけることができるものは選択肢を使用するものですが、黒い背景を持つためには3つのアイテムが必要です。

リサイクルせずにアイテムの背景色を設定する簡単な方法はありませんか?実行時に変更する必要はありません。

+0

ビューが作成されたときのアダプタクラスでは、その位置変数を使用して、必要な項目や背景色に色を設定します。 – Sahil

+0

どのアダプタクラスですか?申し訳ありませんが、私はアンドロイドを初めて使い、何を意味するのか分かりません。 – Fn20

+0

ええ、あなたのアダプタクラスで...あなたはメソッドを使用してposition変数を使用し、それに応じてifまたはswitchを作成します。 – Sahil

答えて

0

EDIT:あなたの質問

adapter = new ListAdapter(ListActivity.this , R.layout.custom_list , items); 
    listView.setAdapter(adapter); 


    public class ListAdapter extends ArrayAdapter <String>{ 

    public ListAdapter(Context context, int textViewResourceId) { 
     super(context, textViewResourceId); 
    } 

    public ListAdapter(Context context, int resource, ArrayList<String> items) { 
     super(context, resource, items); 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     View v = convertView; 

     if (v == null) { 
      LayoutInflater vi; 
      vi = LayoutInflater.from(getContext()); 
      v = vi.inflate(R.layout.itemlistrow, null); 
     } 
     LinearLayout ll = (LinearLayout)v.findViewById(R.id.ll); 
     TextView tv = (TextView)v.findViewById(R.id.tv); 

     if (position == 1) { 
      ll.setBackgroundColor(Color.BLACK); 
      tv.setTextColor(Color.WHITE); 
     } 
     if (position == 3) { 
      ll.setBackgroundColor(Color.BLACK); 
      tv.setTextColor(Color.WHITE); 
     } 
     if (position == 10) { 
      ll.setBackgroundColor(Color.BLACK); 
      tv.setTextColor(Color.WHITE); 
     } 
     tv.setText(items.get(position)); 

     return v; 
    } 

} 

によると、ちょうどitemlistrow.xmlは、私はそれが今、あなたを助けますhopw

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/ll" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView 
     android:id="@+id/tv" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 
</LinearLayout> 

を下回っていることを確認します。

+0

ありがとうございます、私はのために何を使用しますか? アダプターを次のように設定しようとしています。 アダプター= new android.widget.ListAdapter (this、 android.R.layout.simple_list_item_1、items); listView.setAdapter(adapter); – Fn20

+0

私はそれを試しましたが、私はそれを正しく使用しているとは思いません。上記のように私ははエラーを出すが、私はR.id.itemlistrowを何に置き換えるべきかも知らない。 – Fn20

+0

今は走っていますが、下にスクロールすると黒い背景がリサイクルされ、配列のアイテムがリストに表示されません。 – Fn20

関連する問題