2017-10-19 118 views
0

我使用SimpleCursorAdapter來擴展帶有聯繫人姓名的ListView。 在listview.onItemClickListener我改變看法的TextView中的使用下面的代碼的顏色 -在用戶選擇時設置listview選擇的項目背景顏色

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      String a = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
      Toast.makeText(contacts.this, "item clicked : \n"+ a + " " + Integer.toString(position) , Toast.LENGTH_SHORT).show(); 
      TextView tv =(TextView) view.findViewById(R.id.txtName); 

      tv.setTextColor(getResources().getColor(R.color.colorAccent)); 

     } 
    }); 

的事情是,當顏色變爲一個項目它也改變了項目在接下來的頁面時用戶滾動列表。

是否有getView方法,我可以覆蓋SimpleCursorAdapter?

+0

我發現下面的[鏈接]回答我的問題(https://stackoverflow.com/questions/2398767/trying-to-override-getview-in -a-simplecursoradapter-giving-nullpointerexceptio) – Shai

+0

在getView()中將文本顏色更改爲默認值 – nomag

回答

0
 private class ColorTestAdapter extends ArrayAdapter<String> { 
      private final Context context; 
      private final String[] values; 

      public ColorTestAdapter(Context context, String[] values) { 
       super(context, R.layout.list_item, values); 
       this.context = context; 
       this.values = values; 
      } 

      @Override 
      public View getView(int position, View convertView, ViewGroup parent) { 
       LayoutInflater inflater = (LayoutInflater) context 
         .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
       View layout_view = inflater.inflate(R.layout.list_item, parent, false); 
       TextView tv = (TextView) layout_view.findViewById(R.id.list_textview); 
       // Set text 
       tv.setText(values[position]); 
       // Set color depending on position 
       int textColorId = R.color.black; // Default color 
       if(position == 1){ 
         textColorId = R.color.red; 
       } 

       } 
       tv.setTextColor(getResources().getColor(textColorId)); 
       return layout_view; 
      } 
     } 

在OnCreate中

myListView = (ListView)findViewById(R.id.main_listView); 
     ColorTestAdapter adapter = new ColorTestAdapter(this,myLists); 
     myListView.setAdapter(adapter); 
相關問題