我不知道应该怎么做才能实现可选择的 ListView 并在操作栏中显示选定的项目。我想有一种本地且快速的方法可以做到这一点,但我不知道如何搜索它!有人可以帮我吗?
问问题
418 次
1 回答
2
您将在您的 sdk 的示例下找到示例
android-sdk-linux/samples/android-17/ApiDemos/src/com/example/android/apis/view/List16
使用以下内容作为参考并进行相应修改。
活动
public class MainActivity extends ListActivity {
String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy",
"Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi",
"Television", "Thriller"
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView lv = getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
lv.setMultiChoiceModeListener(new ModeCallback());
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, GENRES));
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
getActionBar().setSubtitle("Long press to start selection");
}
private class ModeCallback implements ListView.MultiChoiceModeListener {
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.list_select_menu, menu);
mode.setTitle("Select Items");
return true;
}
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
Toast.makeText(MainActivity.this, "Shared " + getListView().getCheckedItemCount() +
" items", Toast.LENGTH_SHORT).show();
mode.finish();
break;
default:
Toast.makeText(MainActivity.this, "Clicked " + item.getTitle(),
Toast.LENGTH_SHORT).show();
break;
}
return true;
}
public void onDestroyActionMode(ActionMode mode) {
}
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
final int checkedCount = getListView().getCheckedItemCount();
switch (checkedCount) {
case 0:
mode.setSubtitle(null);
break;
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + checkedCount + " items selected");
break;
}
}
}
}
list_select_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/share"
android:title="share"
android:icon="@android:drawable/ic_menu_share"
android:showAsAction="always" />
</menu>
在 res/values-v11/styles.xml 下。使用它会将所选项目设置为蓝色。
<resources>
<style name="AppTheme" parent="android:Theme.Holo.Light"></style>
<style name="activated" parent="AppTheme">
<item name="android:background">?android:attr/activatedBackgroundIndicator</item>
</style>
</resources>
将样式添加到布局的根元素。
style="@style/activated"
快照
于 2013-09-09T12:59:04.710 回答