Android developers often encountered in using ListView, sometimes requires more than just list shows, there is a long list carried out by multiple choice, and bulk delete of the situation, where the record about what they have learned.
First on renderings:
Several core methods need to use:
//设置多选模式,下面的方法基于设置多选模式
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//获取Item选择状态:
list.isItemChecked(i);
//设置Item选择状态
list.setItemChecked(i, true);
//清除全部选中状态
list.clearChoices();
Description of principle
Multi-select mode, ListView when triggered OnItemClick Item is set to true, once again points to false,
We just need to create a isMultiplSelectionMode to pass judgment current multi-select mode
When traversing list.setItemChecked Select () is true;
Traversing list.isItemChecked (i) when unselected is set true to false, false was true,
List.isItemChecked direct traversal is deleted (i) is true can be deleted directly remove the adapter
Pretend depth Source
We know ListView inherits AbsListView,
by looking at the way he isItemChecked source, you can see
...
public boolean isItemChecked(int position) {
if (mChoiceMode != CHOICE_MODE_NONE && mCheckStates != null) {
return mCheckStates.get(position);
}
return false;
}
...
First, determine the currently selected mode is not equal to the default mode of the radio && mCheckStates
not empty this time mCheckStates
to get the current status of the selected item, then we look at the mCheckStates
what in the end is?
/**
* Running state of which positions are currently checked
*/
SparseBooleanArray mCheckStates;
mCheckStates is an example of SparseBooleanArray, SparseBooleanArray implements Cloneable interface, and then down to digress, now know mCheckStates is essentially a preserve of Boolean Array, Array, and this has a relationship with the Items, setItemChecked / isItemChecked are used mCheckStates, acquired Item is the state, he has helped us write logic, we can only make good isItemChecked.
(As if to say and did not say, like, embarrassed |;)
Directly to the source
activity_main.xml
First interface: display of a selected number of TextView, the Button 3, a ListView
<?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="vertical">
<LinearLayout
android:visibility="gone"
android:id="@+id/ItemToolBar"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选择了0项"
android:id="@+id/counttext"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="全选"
android:id="@+id/all"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="反选"
android:id="@+id/unall"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="删除"
android:id="@+id/del"/>
</LinearLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mylistview"/>
</LinearLayout>
listview_item.xml
Of course there Item entry interface, simply, two TextView, a title, a content
<?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="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/lv_text1"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="@+id/lv_text2"/>
</LinearLayout>
MyAdapter.java
ListView adapter, rewritten getView way to let the current state of the visible part of the project to change the background color is selected, on ViewHolder part geiView can look at this article [ optimizations ViewHolder a list ListView common Android development ], it is a kind of short list optimization mode.
public class MyAdapter extends BaseAdapter {
public ArrayList<HashMap<String, Object>> balistItem = new ArrayList<HashMap<>>();
@Override
public int getCount() {
return balistItem.size();
}
@Override
public long getItemId(int p1) {
return p1);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = View.inflate(MainActivity.CONTEXT, R.layout.listview_item, null);
viewHolder.title = convertView.findViewById(R.id.lv_text1);
viewHolder.text = convertView.findViewById(R.id.lv_text2);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.title.setText(balistItem.get(position).get("标题").toString());
viewHolder.text.setText(balistItem.get(position).get("内容").toString());
//判断position位置是否被选中,改变颜色
if (MainActivity.list.isItemChecked(position) && MainActivity.isMultipleSelectionMode) {
convertView.setBackgroundColor(0xffff521d);
} else {
convertView.setBackgroundColor(0xff1E90FF);
}
return convertView;
}
public MyAdapter(List<? extends Map<String, ?>> data) {
this.balistItem = (ArrayList<HashMap<String, Object>>) data;
}
private static class ViewHolder {
TextView title;
TextView text;
public static ViewHolder newsInstance(View convertView) {
ViewHolder holder = (ViewHolder) convertView.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.title = convertView.findViewById(R.id.lv_text1);
holder.text = convertView.findViewById(R.id.lv_text2);
convertView.setTag(holder);
}
return holder;
}
}
}
MainActivity.java
create data and added to the adapter, set up long-press to enter multiple choice mode,
public class MainActivity extends AppCompatActivity {
static ListView list;
static MyAdapter listItemAdapter;//适配器
static boolean isMultipleSelectionMode;//判断进入多选模式
public static ArrayList<HashMap<String, Object>> AdapterList = new ArrayList<>(); //数据
public static Context CONTEXT;
TextView counttext;
LinearLayout ItemToolBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CONTEXT = this.getApplicationContext();
//初始化数据
initData();
counttext = this.findViewById(R.id.counttext);//选中时更改的textview
ItemToolBar = this.findViewById(R.id.ItemToolBar);//多选模式的工具栏
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listItemAdapter = new MyAdapter(AdapterList); //新建并配置ArrayAapeter
list.setAdapter(listItemAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> p, View v, int index,
long arg3) {
if (isMultipleSelectionMode) {
setCountChange();
}
listItemAdapter.notifyDataSetChanged();
}
});
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long itemId) {
if (isMultipleSelectionMode) {
ItemToolBar.setVisibility(View.GONE);
isMultipleSelectionMode = false;
list.clearChoices();//取消选中状态
Toast.makeText(CONTEXT, "退出多选模式", Toast.LENGTH_LONG).show();
} else {
ItemToolBar.setVisibility(View.VISABLE); isMultipleSelectionMode =true;
listItemAdapter.notifyDataSetChanged();
//多选模式
Toast.makeText(CONTEXT, "进入多选模式", Toast.LENGTH_LONG).show();
for(int i = 0;i < listItemAdapter.balistItem.size();i++){
Log.d("del","Item" + i + "的状态:" + list.isItemChecked(i));
}
return true;
}
listItemAdapter.notifyDataSetChanged();
setCountChange();
return false;
}
});
//设置按钮单机事件绑定
setButtonClick();
}
public void setCountChange(){
counttext.setText("选中了" + list.getCheckedItemCount() +"项");
}
public void initData(){
list = this.findViewById(R.id.mylistview);
for(int i = 0;i< 5;i++){
HashMap<String,Object> map = new HashMap<>();
map.put("标题","这是标题" + i);
map.put("内容","这是内容" + i);
AdapterList.add(map);
}
}
public void setButtonClick(){
Button all = this.findViewById(R.id.all);
Button unall = this.findViewById(R.id.unall);
Button del = this.findViewById(R.id.del);
all.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i = 0;i < listItemAdapter.balistItem.size();i++){
list.setItemChecked(i,true);
}
setCountChange();
}
});
unall.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i = 0;i < listItemAdapter.balistItem.size();i++){
if(list.isItemChecked(i)){
list.setItemChecked(i,false);
list.setItemChecked(i,false);
}else {
list.setItemChecked(i,true);
}
}
setCountChange();
}
});
del.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(int i = 0;i < listItemAdapter.balistItem.size();i++){
if(list.isItemChecked(i)){
listItemAdapter.balistItem.remove(i);
listItemAdapter.notifyDataSetChanged();
}
}
list.clearChoices();
setCountChange();
}
});
}
}
demo apk file download address: https: //files.cnblogs.com/files/zzerx/app-debug (1) .apk