自定義類似RadioButton的單選、多選的ListView

很多時候我們在做選擇框的時候會想到RadioButton,但是RadioButton只是一個Button,很難添加豐富的內容,比如添加圖片,文件及說明等。這個時候我們可以通過自定義ListView來實現類似的效果。當然,這也就是在ListView控件中實現點擊選擇或取消的效果。

我們先在layout中放上2個button和一個listview,分別用來單選、多選和自定義的listview。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/btn_select_one"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:text="單選"
        android:textSize="16sp" />

    <Button
        android:id="@+id/btn_select_multi"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:text="多選"
        android:textSize="16sp" />

    <ListView
        android:id="@+id/listview_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginRight="10dip"
        android:layout_marginTop="5dip"
        android:cacheColorHint="@android:color/transparent" />

</LinearLayout>
ListView的單個item的佈局我們放2個imageview和2個textview:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="5dip" >

    <ImageView
        android:id="@+id/iv_icon"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="2" />

    <LinearLayout
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dip"
        android:layout_weight="5"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/tv_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black"
            android:textSize="12sp" />
    </LinearLayout>

	<ImageView
        android:id="@+id/iv_select"
        android:layout_width="0dip"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

</LinearLayout>

佈局寫好了,我們在Java這邊監聽這幾個控件,並且將listview的內容通過方法getListData()來獲取,而listview的單選多選我們通過一個全局的boolean變量來控制,代碼都很簡單,也就沒什麼註釋:

public class MainActivity extends Activity
{
	private ListView mListView;
	private ListViewAdapter mListViewAdapter;		//自定義的Adapter
	
	private Button btn_Select_One;
	private Button btn_Select_Multi;
	
	public static boolean isSelectOne = true;	//用來控制是否單選、多選
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mListView = (ListView)findViewById(R.id.listview_main);
		mListViewAdapter = new ListViewAdapter(MainActivity.this, getListData());
		mListView.setAdapter(mListViewAdapter);
		mListView.setOnItemClickListener(itemClickListener);
		
		btn_Select_One = (Button)findViewById(R.id.btn_select_one);
		btn_Select_One.setOnClickListener(clickListener);
		btn_Select_Multi = (Button)findViewById(R.id.btn_select_multi);
		btn_Select_Multi.setOnClickListener(clickListener);
	}
	
	private OnClickListener clickListener = new OnClickListener()
	{
		
		@Override
		public void onClick(View v)
		{
			// TODO Auto-generated method stub
			switch (v.getId())
			{
				case R.id.btn_select_one:
					isSelectOne = true;
					Toast.makeText(MainActivity.this, "單選", Toast.LENGTH_SHORT).show();
					break;
				case R.id.btn_select_multi:
					isSelectOne = false;
					Toast.makeText(MainActivity.this, "多選", Toast.LENGTH_SHORT).show();
					break;
			}
		}
	};
	
	private OnItemClickListener itemClickListener = new OnItemClickListener()
	{

		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3)
		{
			// TODO Auto-generated method stub
			mListViewAdapter.setSelectItem(position);
		}
	};
	
	private List<Map<String, Object>> getListData()
	{
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		Map<String, Object> item = new HashMap<String, Object>();
		item.put("icon", R.drawable.pay_alipay);
		item.put("title", "支付寶");
		item.put("content", "推薦支付寶用戶使用");
		item.put("select", R.drawable.pay_select);
		list.add(item);

		item = new HashMap<String, Object>();
		item.put("icon", R.drawable.pay_alipay);
		item.put("title", "支付寶");
		item.put("content", "推薦支付寶用戶使用");
		item.put("select", R.drawable.pay_select);
		list.add(item);

		item = new HashMap<String, Object>();
		item.put("icon", R.drawable.pay_alipay);
		item.put("title", "支付寶");
		item.put("content", "推薦支付寶用戶使用");
		item.put("select", R.drawable.pay_select);
		list.add(item);

		item = new HashMap<String, Object>();
		item.put("icon", R.drawable.pay_alipay);
		item.put("title", "支付寶");
		item.put("content", "推薦支付寶用戶使用");
		item.put("select", R.drawable.pay_select);
		list.add(item);

		item = new HashMap<String, Object>();
		item.put("icon", R.drawable.pay_alipay);
		item.put("title", "支付寶");
		item.put("content", "推薦支付寶用戶使用");
		item.put("select", R.drawable.pay_select);
		list.add(item);
		
		return list;
	}

}

實現單選、多選的地方在自定義的Adapter中,單選的話,我們定義一個整型變量selectItem,在點擊listview的item的時候,將item的位置賦值給selectItem,然後再adapter的getview方法中判斷position與selectItem是否相等,相等爲已選擇的,對其做處理,如改背景色,這裏將選擇的圖片設爲可見;

若是多選,則定義了一個HashMap來存儲已經被點擊的item位置和是否選擇鍵值對,點擊item時,若map中無此item或此item值爲false,將其置爲true,表示被選擇,反之,置爲false,表示取消選擇。

/**
 * 自定義可單選、多選的ListView Adapter
 * @author Tony
 */
@SuppressLint("UseSparseArrays")
public class ListViewAdapter extends BaseAdapter
{
	private List<Map<String, Object>> mList;
	private HashMap<Integer, Boolean> mMap = new HashMap<Integer, Boolean>();
	protected LayoutInflater mInflater;
	private int selectItem = -1;

	public ListViewAdapter(Context context, List<Map<String, Object>> list)
	{
		// TODO Auto-generated constructor stub
		this.mList = list;
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount()
	{
		// TODO Auto-generated method stub
		return mList.size();
	}

	@Override
	public Object getItem(int location)
	{
		// TODO Auto-generated method stub
		return mList.get(location);
	}

	@Override
	public long getItemId(int position)
	{
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		// TODO Auto-generated method stub
		ViewHolder mViewHolder;

		if (convertView == null)
		{
			convertView = mInflater.inflate(R.layout.list_item, null);
			mViewHolder = new ViewHolder();
			mViewHolder.iv_Icon = (ImageView) convertView.findViewById(R.id.iv_icon);
			mViewHolder.tv_Title = (TextView) convertView.findViewById(R.id.tv_title);
			mViewHolder.tv_Content = (TextView) convertView.findViewById(R.id.tv_content);
			mViewHolder.iv_Select = (ImageView) convertView.findViewById(R.id.iv_select);

			convertView.setTag(mViewHolder);
		} else
		{
			mViewHolder = (ViewHolder) convertView.getTag();
		}

		mViewHolder.iv_Icon.setImageResource(Integer.parseInt(mList.get(position).get("icon").toString()));
		mViewHolder.tv_Title.setText(mList.get(position).get("title").toString());
		mViewHolder.tv_Content.setText(mList.get(position).get("content").toString());
		mViewHolder.iv_Select.setImageResource(Integer.parseInt(mList.get(position).get("select").toString()));

		if (MainActivity.isSelectOne)
		{
			if (selectItem == position)
			{
				mViewHolder.iv_Select.setVisibility(View.VISIBLE);
			} else
			{
				mViewHolder.iv_Select.setVisibility(View.INVISIBLE);
			}
		} else
		{
			if (mMap.containsKey(position) && mMap.get(position))
			{
				mViewHolder.iv_Select.setVisibility(View.VISIBLE);
			} else
			{
				mViewHolder.iv_Select.setVisibility(View.INVISIBLE);
			}
		}

		return convertView;
	}

	/**
	 * 將被點擊的item的位置傳值過來,如果是單選,則直接賦值爲selectItem;
	 * 若爲多選,則判斷map中是否已有此item,且其值爲true,則代表已經被點擊,
	 * 若再點擊,則變爲false,反之(若無此item或其值爲false),變爲true。
	 * @param item
	 */
	public void setSelectItem(int item)
	{
		if (MainActivity.isSelectOne)
		{
			this.selectItem = item;
		} else
		{
			if (mMap.containsKey(item) && mMap.get(item))
			{
				mMap.put(item, false);
			} else
			{
				mMap.put(item, true);
			}
		}
		notifyDataSetChanged();
	}


	public class ViewHolder
	{
		public ImageView iv_Icon;
		public TextView tv_Title;
		public TextView tv_Content;
		public ImageView iv_Select;
	}
}

完整工程下載:點擊打開鏈接






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章