2

我有一个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);  
            }
});

对于第一个可见项目,一切正常,但是当我滚动列表时,我有一个 NullPointerExceptionat 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);

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

4

2 回答 2

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       
}
于 2012-03-18T12:28:23.957 回答
0

我想你应该使用

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

代替

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

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

于 2012-03-18T11:07:11.697 回答