2014-11-22 47 views
0

我似乎無法鍛鍊如何讓onItemSelectedListender接口工作。我想更改所選項目的顏色,並在取消選擇後將其更改回來。我已經完成了一些閱讀,並且設法使用onItemSelectedListener做了類似的事情。如何使用onItemSelectedListener更改視圖的顏色

我的代碼是

libraryGrid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
     @Override 
     public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 

      //I want to change the color of the view that was just selected 
      view.setBackgroundColor(Color.GRAY); 
      adapterView.getSelectedView().setBackgroundColor(Color.YELLOW); 

     } 

     @Override 
     public void onNothingSelected(AdapterView<?> adapterView) { 
      //How do I access the view that was just unselected to change it's color? 
      adapterView.setBackgroundColor(Color.BLACK); 
     } 
    }); 

回答

0

您保留所選項目的跟蹤和改變從getView方法該項目的背景壁紙

嘗試這種方式..

libraryGrid.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 
     @Override 
     public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 

      mSelectedItem = position; 
       mAdapter.notifyDataSetChanged(); 


     } 

     @Override 
     public void onNothingSelected(AdapterView<?> adapterView) { 

     } 
    }); 

並在你的getView方法中設置所選項目的背景顏色。

@Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     final View view = View.inflate(context, R.layout.item_list, null); 

     if (position == mSelectedItem) { 
      //set Selected color as background on view 
     } 
     else{ 
      //set unSelected color as background on View 
     } 

     return view; 
    } 
+0

感謝您的回覆。我有一個gridView的textViews。原來,點擊textView不算作選擇。所以在我的情況下,我需要使用onItemClickListener而不是onItemSelectedListener,在這種情況下,我需要像你說的那樣記錄狀態。歡呼聲 – 2014-11-22 06:28:42

+0

樂意幫忙.. :) – iMDroid 2014-11-22 08:36:34