GridView中Checkbox全選

效果:


新建一個GridviewAdapter,你可以一目十行的瀏覽過。

都是比較基礎的。

public class GridviewAdapter extends BaseAdapter{
    private ArrayList<Person> list;
    private static HashMap<Integer,Boolean> isSelected;
    private Context context;
    private LayoutInflater inflater = null;
    public GridviewAdapter(ArrayList<Person> list, Context context) {
        this.context = context;
        this.list = list;
        inflater = LayoutInflater.from(context);
        isSelected = new HashMap<Integer, Boolean>();
        initDate();
    }
    private void initDate(){
        for(int i=0; i<list.size();i++) {
            getIsSelected().put(i,false);
        }
    }
    @Override
    public int getCount() {
        return list.size();
    }
    @Override
    public Object getItem(int position) {
        return list.get(position);
    }
    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
            if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.gridviewitem, null);
            holder.name = (TextView) convertView.findViewById(R.id.item_name);
            holder.ID = (TextView) convertView.findViewById(R.id.item_ID);
            holder.cb = (CheckBox) convertView.findViewById(R.id.item_cb);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
            }
        holder.ID.setText(list.get(position).getId());
        holder.name.setText(list.get(position).getName());
        holder.cb.setChecked(getIsSelected().get(position));
        return convertView;
    }
    static class ViewHolder{  
        CheckBox cb;  
        TextView name;  
        TextView ID;  
    }
    public static HashMap<Integer,Boolean> getIsSelected() {
        return isSelected;
    }
    public static void setIsSelected(HashMap<Integer,Boolean> isSelected) {
        GridviewAdapter.isSelected = isSelected;
    }

}
需要留意的是:

public static HashMap<Integer,Boolean> getIsSelected() {
        return isSelected;
    }
    public static void setIsSelected(HashMap<Integer,Boolean> isSelected) {
        GridviewAdapter.isSelected = isSelected;
    }

用來保存選擇狀態

我們新建一個Activity來看看效果:

public class MainActivity extends Activity implements OnClickListener {

	private GridView gd;
	private GridviewAdapter mAdapter;
	private ArrayList<Person> persons;
	private Button bt_selectall;
	private Button bt_cancel;
	private Button bt_deselectall;
	private Button bt_sumit;
	private int checkNum; // 記錄選中的條目數量
	private TextView tv_show;// 用於顯示選中的條目數量
	List<String> selectID = new ArrayList<String>(); //選中的ID

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		initData();
		gd.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				ViewHolder holder = (ViewHolder) arg1.getTag();
				holder.cb.toggle();
				GridviewAdapter.getIsSelected().put(arg2, holder.cb.isChecked());
				if (holder.cb.isChecked() == true) {
					checkNum++;
				} else {
					checkNum--;
				}
				tv_show.setText("已選中" + checkNum + "項");
			}
		});
	}
	/**
	 * 初始化數據
	 */
	private void initData() {
		Person mPerson;
		for (int i = 1; i <= 40; i++) {
			mPerson = new Person();
			mPerson.setName("aikaifa" + i);
			// mPerson.setId(Character.valueOf((char)(i+65))+" ");
			mPerson.setId(i + "");
			persons.add(mPerson);
		}
		mAdapter = new GridviewAdapter(persons, this);
		gd.setAdapter(mAdapter);
	}

	/**
	 * 刷新
	 */
	private void dataChanged() {
		mAdapter.notifyDataSetChanged();
		tv_show.setText("已選中" + checkNum + "項");
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		gd = (GridView) findViewById(R.id.gd);
		bt_selectall = (Button) findViewById(R.id.bt_selectall);
		bt_cancel = (Button) findViewById(R.id.bt_cancelselectall);
		bt_deselectall = (Button) findViewById(R.id.bt_deselectall);
		bt_sumit = (Button) findViewById(R.id.bt_submit);
		tv_show = (TextView) findViewById(R.id.tv);
		persons = new ArrayList<Person>();
		
		bt_selectall.setOnClickListener(this);
		bt_cancel.setOnClickListener(this);
		bt_deselectall.setOnClickListener(this);
		bt_sumit.setOnClickListener(this);
	}

	/**
	 * 全選
	 */
	private void selectAll() {
		for (int i = 0; i < persons.size(); i++) {
			GridviewAdapter.getIsSelected().put(i, true);
		}
		// 數量設爲list的長度
		checkNum = persons.size();
		dataChanged();
	}

	/**
	 * 全不選
	 */
	private void cancelselectall() {
		// 遍歷list的長度,將已選的按鈕設爲未選
		for (int i = 0; i < persons.size(); i++) {
			if (GridviewAdapter.getIsSelected().get(i)) {
				GridviewAdapter.getIsSelected().put(i, false);
				checkNum--;// 數量減1
			}
		}
		dataChanged();
	}

	/**
	 * 反選
	 */
	private void deselectall() {
		// 遍歷list的長度,將已選的設爲未選,未選的設爲已選
		for (int i = 0; i < persons.size(); i++) {
			if (GridviewAdapter.getIsSelected().get(i)) {
				GridviewAdapter.getIsSelected().put(i, false);
				checkNum--;
			} else {
				GridviewAdapter.getIsSelected().put(i, true);
				checkNum++;
			}
		}
		dataChanged();
	}

	/**
	 * 提交
	 */
	private void submit() {
		selectID.clear();
		for (int i = 0; i < mAdapter.getIsSelected().size(); i++) {
			if (mAdapter.getIsSelected().get(i)) {
				selectID.add(persons.get(i).getId());

			}
		}

		if (selectID.size() == 0) {
			AlertDialog.Builder builder1 = new AlertDialog.Builder(
					MainActivity.this);
			builder1.setMessage("沒有選中任何記錄");
			builder1.show();
		} else {
			StringBuilder sb = new StringBuilder();

			for (int i = 0; i < selectID.size(); i++) {

				sb.append("ID=" + selectID.get(i) + "  ");

			}
			AlertDialog.Builder builder2 = new AlertDialog.Builder(MainActivity.this);
			builder2.setMessage(sb.toString());
			builder2.show();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_selectall:
			selectAll();
			break;
		case R.id.bt_cancelselectall:
			cancelselectall();
			break;
		case R.id.bt_deselectall:
			deselectall();
			break;
		case R.id.bt_submit:
			submit();
			break;
		}
	}
}

這裏定義了一個實體類Person

public class Person {
	private String name;
	private String Id;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getId() {
		return Id;
	}
	public void setId(String id) {
		Id = id;
	}	
}

剩下兩個xml佈局文件:

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
>
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <Button
            android:id="@+id/bt_selectall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全選" />

        <Button
            android:id="@+id/bt_cancelselectall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="全不選" />

        <Button
            android:id="@+id/bt_deselectall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="反選" />

        <Button
            android:id="@+id/bt_submit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="提交" />

    </LinearLayout>

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <GridView
        android:id="@+id/gd"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:numColumns="2" />

</LinearLayout>

gridviewitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >
    <TextView
        android:id="@+id/item_ID"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:visibility="gone" />
    <TextView
        android:id="@+id/item_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical" />
    <CheckBox
        android:id="@+id/item_cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:gravity="center_vertical" />
</LinearLayout>


開發者最多人關注的微信公衆號

傳播正能量,分享技術難題


更多源碼請關注微信公衆號:aikaifa ,第一時間推送博文源碼


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