如何在ListActivity中突出显示所选项目

时间:2013-04-15 07:15:07

标签: android highlight listactivity

我创建了一个从ListActivity类派生的RecordActivity类,并为.xml中定义的ListView设置了选择模式和选择器。默认行为是所选项目仅在我按下时才会突出显示。我想保持所选项目突出显示。我试图覆盖ArrayAdapter的getView方法,但是,它不起作用。任何帮助将不胜感激。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="vertical" >

   <ListView  android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>     
</LinearLayout>

public class RecordsActivity extends ListActivity {
   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.records);

      List<Record> values = getAllRecords();
      // Use the SimpleCursorAdapter to show the
      // elements in a ListView
      adapter = new ArrayAdapter<Record>(this, android.R.layout.simple_list_item_1, 
                                                            values);
      setListAdapter(adapter);    
      getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
      getListView().setSelector(android.R.color.holo_red_dark);
   }

   @Override
   protected void onListItemClick(ListView l, View v, int position, long id) {
      selectedItem = position;
      v.setSelected(true);      
   }
}

3 个答案:

答案 0 :(得分:4)

尝试使用simple_list_item_activated_1

adapter = new ArrayAdapter<Record>(this, android.R.layout.simple_list_item_activated_1, 
                                                        values);

答案 1 :(得分:1)

    private int selectedValue;
    private View row;

  ListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            selectedValue=arg2;
            if(row!=null)
            {
                                row.setBackgroundResource(R.drawable.group_item_normal);
            }
            row=arg1;
        arg1.setBackgroundResource(R.drawable.group_item_pressed);

        }
    });

在getView()中执行: - v是由getView()返回的对象

  if(selectedValue==position)
        {
            v.setBackgroundResource(R.drawable.group_item_pressed);

        }
        else{
            v.setBackgroundResource(R.drawable.group_item_normal);

        }

答案 2 :(得分:0)

尝试此操作,在蜂窝或更大的蜂窝状态下,所选项目将保持突出显示。由于android.R.layout.simple_list_item_activated_1仅适用于蜂窝版或更高版本,因此您应该添加这样的布局以支持旧平台。

int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
                : android.R.layout.simple_list_item_1;


adapter = new ArrayAdapter<Record>(this, layout, values);