<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" > <ListView android:id="@+id/lv" android:layout_width="wrap_content" android:layout_height="0dp" android:layout_weight="5" > </ListView> <LinearLayout android:layout_width="fill_parent" android:layout_height="0dp" android:orientation="horizontal" android:layout_weight="1" > <Button android:id="@+id/btn_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="全选" /> <Button android:id="@+id/btn_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="反选" /> <Button android:id="@+id/btn_3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="确定" /> </LinearLayout> </LinearLayout>
布局文件
package com.example.listview; import android.os.Bundle; import android.app.Activity; import android.text.TextUtils; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends Activity { private ListView lv; private String[] data = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv = (ListView) findViewById(R.id.lv); lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, data)); lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); //全选按钮 findViewById(R.id.btn_1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { for (int i = 0; i < data.length; i++) { //遍历并设置所有的为选中状态 lv.setItemChecked(i, true); } } }); //反选按钮 findViewById(R.id.btn_2).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //遍历所有,如果选中的设置为否 , 如果没有选中的设置为是 for (int i = 0; i < data.length; i++) { if (lv.isItemChecked(i)) { lv.setItemChecked(i, false); } else { lv.setItemChecked(i, true); } } } }); //获得内容并输入 findViewById(R.id.btn_3).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String s = ""; for (int i = 0; i < data.length; i++) { if (lv.isItemChecked(i)) { s += lv.getItemAtPosition(i).toString()+" "; } } Toast.makeText(MainActivity.this, s, 1000).show(); } }); } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }