리스트를 long click 후에 선택한 항목을 삭제하면 다중 삭제되는 안드로이드 예제입니다.
activity_main.xml
<RelativeLayout 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"
tools:context=".MainActivity">
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</RelativeLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/activatedBackgroundIndicator"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="5sp"
android:textSize="20sp" />
</LinearLayout>
MyListViewAdapter.java
package com.asukim.deletemultipleselectedlistview;
import java.util.List;
import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListViewAdapter extends ArrayAdapter<String> {
Context myContext;
LayoutInflater inflater;
List<String> DataList;
private SparseBooleanArray mSelectedItemsIds;
//context 와 arrayList를 얻기위한 생성자
public MyListViewAdapter(Context context, int resourceId, List<String> lists) {
super(context, resourceId, lists);
mSelectedItemsIds = new SparseBooleanArray();
myContext = context;
DataList = lists;
inflater = LayoutInflater.from(context);
}
//아이템 컨테이너 클래스
private class ViewHolder {
TextView textView;
ImageView imageView;
}
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.item, null);
//item.xml에서 textview를 선택.
holder.textView = (TextView) view.findViewById(R.id.textView);
//item.xml에서 imageView를 선택.
holder.imageView = (ImageView) view.findViewById(R.id.imageView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
//배열중에 해당 position값의 정보를 textView에 출력
holder.textView.setText(DataList.get(position).toString());
//배열중에 해당 position값의 정보를 imageView에 출력
holder.imageView.setImageResource(R.mipmap.ic_launcher);
return view;
}
@Override
public void remove(String object) {
DataList.remove(object);
notifyDataSetChanged();
}
//업데이트 또는 삭제 후 목록 가져 오기
public List<String> getMyList() {
return DataList;
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
//선택 해제 후 선택 제거
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
//선택시 체크된 된 항목
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
//선택한 항목 수 가져 오기
public int getSelectedCount() {
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
}
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/selectAll"
android:title="Select All" />
<item
android:id="@+id/delete"
android:title="Delete" />
</menu>
MainActivity.java
package com.asukim.deletemultipleselectedlistview;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.ListView;
public class MainActivity extends Activity {
List myList;
ListView listView;
MyListViewAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = new ArrayList();
//임시로 데이터 입력
for (int i = 1; i < 30; i++) {
myList.add("Item " + i);
}
listView = (ListView) findViewById(R.id.listview);
//adapter 생성후 layout이랑 배열 연결
adapter = new MyListViewAdapter(this, R.layout.item, myList);
listView.setAdapter(adapter);
//다중 삭제를 위한 선택 모드
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.selectAll:
final int checkedCount = myList.size();
//항목을 이미 선택하거나 선택한 경우 제거하거나 선택 취소 후 다시 모두 선택
adapter.removeSelection();
for (int i = 0; i < checkedCount; i++) {
listView.setItemChecked(i, true);
// listviewadapter.toggleSelection(i);
}
mode.setTitle(checkedCount + " Selected");
return true;
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("선택한 항목을 삭제하겠습니까?");
builder.setNegativeButton("No", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setPositiveButton("Yes", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
String selecteditem = adapter.getItem(selected.keyAt(i));
//다음에 선택한 항목 제거
adapter.remove(selecteditem);
}
}
mode.finish();
selected.clear();
}
});
AlertDialog alert = builder.create();
alert.setIcon(R.mipmap.ic_launcher_round);// dialog Icon
alert.setTitle("Confirmation"); // dialog Title
alert.show();
return true;
default:
return false;
}
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
final int checkedCount = listView.getCheckedItemCount();
mode.setTitle(checkedCount + " Selected");
adapter.toggleSelection(position);
}
});
}
}
Git
스크린샷
728x90
반응형
'AOS' 카테고리의 다른 글
splash 화면 (0) | 2020.01.31 |
---|---|
생명주기 (0) | 2020.01.30 |
개인정보보호 처리방침 (0) | 2020.01.28 |
Ripple Effect(물결효과) (0) | 2020.01.23 |
Full Screen모드(title bar 제거, status bar 제거) (0) | 2020.01.18 |