按住列表项

时间:2014-09-18 10:26:51

标签: android

单击时如何设置选定列表中的某些项目?

Google地图应用示例:

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个帮助你 方法1:获取当前选定的位置

 OnItemClickListener listViewOnItemClick = new OnItemClickListener() {

@Override
 public void onItemClick(AdapterView<?> adapter, View arg1, int position, long id) {
          mSelectedItem = position;
          mAdapter.notifyDataSetChanged();
 }
 };

And override the getView method of your adapter:

@Override
 public View getView(int position, View convertView, ViewGroup parent) {
 final View view = View.inflate(context, R.layout.item_list, null);

if (position == mSelectedItem) {
     // set your color
}

  return view;

}

Method 2:


first put this in your listview

android:listSelector="@drawable/list_selector"
Then create xml files in drawable to control the diferent states

@绘制/ list_selector

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/list_item_bg_normal" android:state_activated="false"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_pressed="true"/>
<item android:drawable="@drawable/list_item_bg_pressed" android:state_activated="true"/>
</selector>

@绘制/ list_item_bg_normal:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
  android:startColor="@color/list_background"
  android:endColor="@color/list_background"
  android:angle="90" />
</shape>

@绘制/ list_item_bg_pressed:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="@color/list_background_pressed"
      android:endColor="@color/list_background_pressed"
      android:angle="90" />
</shape>

在ListView选择中:

listView.setOnItemClickListener(new OnItemClickListener() {

         @Override
         public void onItemClick(AdapterView<?> parent, View view, int position,long arg3) {
             view.setSelected(true);
             ...
         }
    }