2

私はListView、ユーザーがそのアイテムの1つをクリックすると、そのアイテムを青色にしたいと思っています。これを行うためにonCreate()、アクティビティのメソッドでListView、ユーザークリックのリスナーを設定しました。

m_listFile=(ListView)findViewById(R.id.ListView01);  
      m_listFile.setOnItemClickListener(new OnItemClickListener() {  

            public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {  
                arg0.getChildAt(arg2).setBackgroundColor(Color.BLUE);  
            }
});

最初に表示されるアイテムはすべて正常に機能しますが、リストをスクロールすると NullPointerException、値が正しいアイテムインデックスの位置にある arg0.getChildAt(arg2).setBackgroundColor(...)場合でも、が表示されます。arg2

ListViewは2つのラインアイテム構造を持っています、私がロードするとき、ListView私はこのアダプターを使用します:

 SimpleAdapter sa = new SimpleAdapter(
            getApplicationContext(), 
            expsList, 
            R.layout.listelement, 
            new String[] { "screen_name","text" },
            new int[] { R.id.Name, R.id.Value}) {

      };

      m_listFile.setAdapter(sa);

この問題を解決する方法がわかりません。助けてもらえますか?

4

2 に答える 2

2

SimpleAdapter次のように拡張できます。

private class MyAdapter extends SimpleAdapter {

        public MyAdapter(Context context, List<? extends Map<String, ?>> data,
                int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView,   parent);
            v.setBackgroundColor(Color.BLACK); //or whatever is your default color
              //if the position exists in that list the you must set the background to BLUE
          if(pos!=null){
            if (pos.contains(position)) {
                v.setBackgroundColor(Color.BLUE);
            }
          }
            return v;
        }

    }

次に、アクティビティに次のようなフィールドを追加します。

//this will hold the cliked position of the ListView
ArrayList<Integer> pos = new ArrayList<Integer>();

アダプターを設定します。

sa = new MyAdapter(
            getApplicationContext(), 
            expsList, 
            R.layout.listelement, 
            new String[] { "screen_name","text" },
            new int[] { R.id.Name, R.id.Value}) {

      };
m_listFile.setAdapter(sa);

行をクリックすると:

    public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {  
                    // check before we add the position to the list of clicked positions if it isn't already set
                if (!pos.contains(position)) {
                pos.add(position); //add the position of the clicked row
            }
        sa.notifyDataSetChanged(); //notify the adapter of the change       
}
于 2012-03-18T12:28:23.957 に答える
0

私はあなたが使うべきだと思います

arg0.getItemAtPosition(arg2).setBackgroundColor(Color.BLUE);

それ以外の

arg0.getChildAt(arg2).setBackgroundColor(Color.BLUE);

これは、Androidデベロッパーリファレンスがここで述べていることです

于 2012-03-18T11:07:11.697 に答える