2012-03-18 120 views
2

我有一個ListView,當用戶點擊其中一個項目時,我希望該項目變成藍色。爲了做到這一點,在ListView活動的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); 
      } 
}); 

一切工作正常,第一個可見的物品,但是當我滾動列表,我有一個 NullPointerExceptionarg0.getChildAt(arg2).setBackgroundColor(...),即使arg2價值有正確的項目索引位置。

ListView有兩行項目結構,當我加載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); 

我不知道如何解決這個問題。我可以得到一些幫助嗎?

+0

你使用自定義適配器爲你的'ListView'? – Luksprog 2012-03-18 11:22:29

+0

我修改了我的第一篇文章 – Ant4res 2012-03-18 11:42:53

回答

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  
} 
+0

對不起,延遲很大......非常感謝,它完美無缺! – Ant4res 2012-03-29 14:04:55

0

我猜你應該使用

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

,而不是

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

它是什麼的Android開發者參考說here

+0

謝謝,但是我不能用那種方式使用setBackgroundColor方法... – Ant4res 2012-03-18 11:18:23

+0

你可以施放這個物品嗎? – Vossi 2012-03-18 11:21:43

+1

@Vossi不,他不能施展它們。 getItemAtPosition()返回與該行關聯的數據(例如,如果適配器應該顯示「字符串」,則該方法將從該行返回字符串)而不是行視圖。 – Luksprog 2012-03-18 11:26:19