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

时间:2018-02-22 17:02:44

标签: java android listview

在此代码中ListView正在运行。但是,我需要知道如何更改列表中出现的文本的颜色。

这是我的代码。

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);`

2 个答案:

答案 0 :(得分:0)

覆盖getView(),如Ziems答案(How to use getview() with a SimpleAdapter in Android?)所示。在getView中获取对要修改的Textviews的引用并设置其textcolor。

答案 1 :(得分:0)

您需要CustomAdapter扩展SimpleAdapter才能获得ListView自定义项目。我建议像这样实施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
    }
}

您需要先使用您拥有的项目初始化CustomAdapter。然后,只需将适配器设置为ListView,然后根据其位置修改TextView