更改列表视图的第一行/最后一行的背景颜色

时间:2016-12-28 16:54:08

标签: android listview

我使用此代码填充列表视图

public class FillList extends AsyncTask<String, String, String> {

    List<Map<String, String>> prolist = new ArrayList<Map<String, String>>();

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onPostExecute(String r) {

        String[] from = {"D", "C", "B","A"};
        int[] views = { R.id.lblPrice,R.id.lblAmount,R.id.lblDescription,R.id.lblDate};
        final SimpleAdapter ADA = new SimpleAdapter(Products.this,
                prolist, R.layout.lsttemplate, from,
                views);
        listview.setAdapter(ADA);

    }

    @Override
    protected String doInBackground(String... params) {

          Map<String, String> datanum = new HashMap<String, String>();

          datanum.put("D", "price");
          datanum.put("C", "amount");
          datanum.put("B", "description");
          datanum.put("A", "date");
          prolist.add(datanum);

          while (rs.next()) {
              datanum = new HashMap<String, String>();


              datanum.put("D", rs.getString("Bes"));
              datanum.put("C", rs.getString("Bed"));
              datanum.put("B", rs.getString("Sharh"));
              datanum.put("A", rs.getString("Date"));
              prolist.add(datanum);

          }
    }               
}

我使用此代码

更改第一行ListView的背景颜色
listview.getChildAt(0).setBackgroundColor(Color.parseColor("#7092bf"));

现在一切正常,第一行改变了背景颜色

但是,

当我向下滚动ListView时,ListView的其他一行也改变了背景颜色。

我只想更改ListView的第一行。

如果我想更改最后一行的背景颜色,我该怎么办?

2 个答案:

答案 0 :(得分:2)

我建议您继承SimpleAdapter并覆盖getView方法:

public class MySimpleAdapter extends SimpleAdapter {
  public MySimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
    super(context, data, resource, from, to);
  }
  public View getView(int position, View convertView, ViewGroup parent) {  
    View view = super.getView(position, convertView, parent);
    if (position == 0) {
      // set special background for first view
      view.setBackgroundColor(...);
    } else if (position == getCount() - 1) {
      // set special background on last view
      view.setBackgroundColor(...);
    } else {
      // set normal background on other views
      view.setBackgroundColor(...);
    }
    return view;
  }
}

这实现了什么:这是ListView调用的方法,用于决定在给定位置的特定项目在屏幕上显示的视图。您现在可以访问该视图,因此您应该在此处进行修改。

请记住还要将背景设置为正常 - 当屏幕的视图滚动时,它将被回收,这意味着它可以在以后用于在列表中显示不同的项目,这可能会或可能会不是第一个。

使用新适配器:

    final MySimpleAdapter ADA = new MySimpleAdapter(Products.this,
            prolist, R.layout.lsttemplate, from,
            views);
    listview.setAdapter(ADA);

答案 1 :(得分:0)

这是为了节省内存。 Android操作系统将不在屏幕上的视图发送到堆或缓存中的其他位置。因此,滚动时索引0处的视图会发生变化。

要解决此问题,请为第一个列表视图添加标签,并使用标签更改背景颜色。 findViewWithTagTraversal会帮助你

相关问题