简体   繁体   English

如何更改从数据库中选择的ListView项的颜色

[英]How to change the color of ListView items which is selected form a database

In this code the ListView is working. 在此代码中, ListView运行正常。 However, I need to know how to change the color of the text which is appearing in the list. 但是,我需要知道如何更改列表中显示的文本的颜色。

This is my code. 这是我的代码。

ArrayList<HashMap<String,String>>allist=new  ArrayList<HashMap<String,String>>();
String[] s1=ou.split("@");

for(int i=0;i<s1.length;i++) {
  String []s2=s1[i].split("#");
  HashMap<String,String>hmap=new HashMap<String,String>();

  hmap.put("a", s2[0]);
  hmap.put("b", s2[1]);
  hmap.put("c",s2[2]);
  hmap.put("d", s2[3]);
  hmap.put("e",s2[4]);
  hmap.put("f",s2[5]);
  hmap.put("g",s2[6]);
  allist.add(hmap);
}

ListAdapter lis=new SimpleAdapter(
  getApplicationContext(),
  allist,
  R.layout.calendar_layout,
  new String[] {"a","b","c","d","e","f","g"},
  new int[] {R.id.textView1, R.id.textView2, R.id.textView3, R.id.textView4, R.id.textView5, R.id.textView6, R.id.textView7}
);
lv.setAdapter(lis);`

Override the getView() as shown in Ziems answer ( How to use getview() with a SimpleAdapter in Android? ). 覆盖Ziems答案中所示的getView()( 如何在Android的SimpleAdapter中使用getview()? )。 In the getView get a reference to the Textviews you want to modify and set their textcolor. 在getView中,获取要修改的Textview的引用并设置其textcolor。

You need to have a CustomAdapter which extends SimpleAdapter to get the items in your ListView customized. 您需要有一个CustomAdapter ,它扩展了SimpleAdapter才能自定义ListView的项目。 I can suggest implementing your CustomAdapter like this. 我可以建议像这样实现您的CustomAdapter

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View view=super.getView(position, convertView, parent);
        TextView yourTextViewForEachItem = (TextView) view.findViewById(R.id.text_view);

        // Now set the color of your textview
        yourTextViewForEachItem.setColor(Color.RED);

        return view;
    }

    @Override
    public int getCount() {
        int count=arrayList.size(); //counts the total number of elements from the arrayList.
        return count; //returns the total count to adapter
    }
}

You need to initialize your CustomAdapter first with the items that you have. 您首先需要使用您拥有的项目初始化CustomAdapter Then just set the adapter into your ListView and modify your TextView based on their position. 然后只需将适配器设置到ListView然后根据其位置修改TextView

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM