设置ListView项目背景颜色的问题

时间:2012-03-18 11:00:35

标签: android background android-listview simpleadapter

我有一个ListView,当用户点击其中一个项目时,我希望该项目变为蓝色。为了做到这一点,在onCreate()活动的ListView方法中,我为用户点击设置了一个监听器。

m_listFile=(ListView)findViewById(R.id.ListView01);  
      m_listFile.setOnItemClickListener(new OnItemClickListener() {  

            public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {  
                arg0.getChildAt(arg2).setBackgroundColor(Color.BLUE);  
            }
});

对于第一个可见项目,一切正常,但是当我滚动列表时,我就是一个 NullPointerException arg0.getChildAt(arg2).setBackgroundColor(...),即使arg2值具有正确的商品索引位置。

我的ListView有两行项目结构,当我加载ListView我使用此适配器时:

 SimpleAdapter sa = new SimpleAdapter(
            getApplicationContext(), 
            expsList, 
            R.layout.listelement, 
            new String[] { "screen_name","text" },
            new int[] { R.id.Name, R.id.Value}) {

      };

      m_listFile.setAdapter(sa);

我不明白如何解决这个问题。我可以得到一些帮助吗?

2 个答案:

答案 0 :(得分:2)

您可以像这样扩展SimpleAdapter

private class MyAdapter extends SimpleAdapter {

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

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View v = super.getView(position, convertView,   parent);
            v.setBackgroundColor(Color.BLACK); //or whatever is your default color
              //if the position exists in that list the you must set the background to BLUE
          if(pos!=null){
            if (pos.contains(position)) {
                v.setBackgroundColor(Color.BLUE);
            }
          }
            return v;
        }

    }

然后在您的活动中添加如下字段:

//this will hold the cliked position of the ListView
ArrayList<Integer> pos = new ArrayList<Integer>();

并设置适配器:

sa = new MyAdapter(
            getApplicationContext(), 
            expsList, 
            R.layout.listelement, 
            new String[] { "screen_name","text" },
            new int[] { R.id.Name, R.id.Value}) {

      };
m_listFile.setAdapter(sa);

单击行时:

    public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {  
                    // check before we add the position to the list of clicked positions if it isn't already set
                if (!pos.contains(position)) {
                pos.add(position); //add the position of the clicked row
            }
        sa.notifyDataSetChanged(); //notify the adapter of the change       
}

答案 1 :(得分:0)

我猜你应该使用

arg0.getItemAtPosition(arg2).setBackgroundColor(Color.BLUE);

而不是

arg0.getChildAt(arg2).setBackgroundColor(Color.BLUE);

这是Android开发人员参考所说的here

相关问题