- package com.example.listviewselectmode;
- import android.R.integer;
- import android.os.Bundle;
- import android.app.ListActivity;
- import android.app.ListActivity;
- import android.view.ActionMode;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.widget.AbsListView.MultiChoiceModeListener;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
- import android.widget.Toast;
- public class MainActivity extends ListActivity {
- String[] itemsStrings={"a","b","c","d","e"};
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- ListView listView=getListView();
- //注意此处没有setContentView那一项
- listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
- listView.setMultiChoiceModeListener(new ModeChoice());
- //注意该adapter的第二个参数为android.R.layout.simple_list_item_checked
- ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_checked, itemsStrings);
- setListAdapter(adapter);
- }
- @Override
- protected void onPostCreate(Bundle savedInstanceState) {
- // TODO Auto-generated method stub
- getActionBar().setTitle("long press to select");
- super.onPostCreate(savedInstanceState);
- }
- class ModeChoice implements MultiChoiceModeListener{
- @Override
- public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
- // TODO Auto-generated method stub
- int count=getListView().getCheckedItemCount();
- switch (item.getItemId()) {
- case R.id.share:
- Toast.makeText(getApplicationContext(), "you share "+count+"项", 1000).show();
- break;
- default:
- Toast.makeText(MainActivity.this, "Clicked " + item.getTitle(),
- Toast.LENGTH_SHORT).show();
- break;
- }
- return true;
- }
- private void setSubtitle(ActionMode mode) {
- // TODO Auto-generated method stub
- int count=getListView().getCheckedItemCount();
- switch (count) {
- case 0:
- mode.setSubtitle("");
- break;
- case 1:
- mode.setSubtitle("you select one item");
- break;
- default:
- mode.setSubtitle("you select"+count+"items");
- break;
- }
- }
- @Override
- public boolean onCreateActionMode(ActionMode mode, Menu menu) {
- // TODO Auto-generated method stub
- getMenuInflater().inflate(R.menu.main, menu);
- mode.setSubtitle("select item");
- setSubtitle(mode);
- //此处需注意需要返回true
- return true;
- }
- @Override
- public void onDestroyActionMode(ActionMode mode) {
- // TODO Auto-generated method stub
- }
- @Override
- public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
- // TODO Auto-generated method stub
- return false;
- }
- @Override
- public void onItemCheckedStateChanged(ActionMode mode, int position,
- long id, boolean checked) {
- // TODO Auto-generated method stub
- setSubtitle(mode);
- }
- }
- }
listview 的 selection mode 训练小例子
最新推荐文章于 2022-09-16 08:55:37 发布