有时app会需要点击某个item并实现选中的效果,例如做pad时用Fragment实现的左侧列表右侧内容的效果,点击左侧某一个item后会高亮选中
有时简单的使用setSelected(boolean b)或setSelection(int position)会不成功,需要重写Adapter,并在getView中进行处理
package com.example.selectitemtest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private ListView lv;
private List
代码中红色标注处就是重点,lv.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);这句话必须要加
Defines the choice behavior for the List. By default, Lists do not have any choice behavior (CHOICE_MODE_NONE
). By setting the choiceMode to CHOICE_MODE_SINGLE
, the List allows up to one item to be in a chosen state. By setting the choiceMode to CHOICE_MODE_MULTIPLE
, the list allows any number of items to be chosen.
实现效果如下