-4

这是我的代码。这里所选行的背景颜色正在改变。但是在滚动未选中视图的背景颜色后也发生了变化。我想防止这个问题。有什么帮助吗?

  public class ListDemoActivity extends ListActivity {
         String[] names = {
                    "Dwight",
                    "Kennedy",
                    "Johnson",
                    "Richard",
                    "Gerald",
                    "Jimmy",
                    "Ronald",
                    "George",
                    "Bill",
                    "B. Bush",
                    "Rana"
            };
         View view;
         int posn = -1;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, names));
        }
        @Override
        protected void onListItemClick(ListView l, View v, int position, long id) {



    Log.i("Log", "Clicked posn"+position);
    Log.i("Log", "id is: "+id);
    if(posn == -1)
    {
        v.setBackgroundResource(R.color.blue);
    //  l.getChildAt(position).setBackgroundResource(R.color.blue);
        view = v;
        posn = position;    
    }
    else if (posn == position)
    {
        v.setBackgroundResource(R.color.blue);
        //l.getChildAt(position).setBackgroundResource(R.color.blue);
    }
    else
    {
        Log.i("Log", "Count of child:  "+l.getChildCount());
    //  View view = l.getChildAt(posn);
    //  Log.i("Log", "Position: "+view.)
        //view.setBackgroundResource(R.color.black);

        //view = l.getChildAt(position);
        //view.setBackgroundResource(R.color.blue);

        view.setBackgroundResource(R.color.black);
        v.setBackgroundResource(R.color.blue);
        view = v;
        posn = position;
    }
    }
}
4

1 回答 1

1

这是因为 ListView 通过它的适配器重用了它的单元格;当一个单元格被滚动出视图时,它会被放在底部,所以如果你把它涂成蓝色并滚动它,它就会出现在下面。

您可以编写一个简单的自定义适配器,在其中跟踪您想要着色的单元格,并在getView(..)您必须覆盖的方法中相应地着色。另请参阅ListViews 上的此视频

于 2012-06-26T07:33:38.890 回答