2016-02-19 57 views
0

我使用這個代碼listview的背景顏色沒有改變。我如何解決它?

ListView lv = getListView(); 
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      TextView idno = (TextView) view.findViewById(R.id.idno); 
      TextView fullname = (TextView) view.findViewById(R.id.fullname); 
      TextView remark = (TextView) view.findViewById(R.id.remark); 
      new DisplayStudent().execute("Update", idno.getText().toString()); 
      if(remark.getText().toString().equals("absent")) { 
       if(isStudentLate) { 
        view.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorLate)); 
        fullname.setTextColor(Color.WHITE); 
        remark.setText("late"); 
       } 
       else { 
        view.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPresent)); 
        fullname.setTextColor(Color.WHITE); 
        remark.setText("present"); 
       } 
      } 
      else if(remark.getText().toString().equals("present") || remark.getText().toString().equals("late")) { 
       view.setBackgroundColor(Color.WHITE); 
       fullname.setTextColor(Color.BLACK); 
       remark.setText("absent"); 
      } 
     } 
    }); 
    ((BaseAdapter)getListView().getAdapter()).notifyDataSetChanged(); 

每次我點擊一個項目,該項目的背景顏色我拍了拍應該改變。爲什麼它沒有改變?我試圖刪除((BaseAdapter)getListView().getAdapter()).notifyDataSetChanged();它確實會改變,但當我向下滾動並再次向上滾動時,它會回到原來的背景顏色。

例如。一個項目的背景顏色是白色的。當我點擊該項目時,它變爲綠色。那很完美。但是,當我向下滾動並再次向上滾動時,我點擊的項目變回白色。我該如何解決?

+0

這是因爲列表視圖重用自己的看法。您必須爲學生維護一個單獨的數組或哈希映射,以確定它們是否存在或不存在。然後在你的listAdapter的getView中使用這個信息來相應地膨脹視圖。 – Frosty

+0

像frosty說Listview回收它的行。 。根據您的選擇,重構您的代碼以更改Adapter.getView方法中的背景顏色。 –

回答

0

嘗試在你的ListView標籤設置這樣的:

android:cacheColorHint="#00000000" 

而且也試試這個:

android:background="color code here"