这是我的xml代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/TaskName"
/>
<Button
android:id="@+id/addBtn"
android:text="Add New Item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="addItems"/>
<Button
android:id="@+id/deleteBtn"
android:text="Delete completed tasks"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="deleteItems"
/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
/>
这是我的java代码
package com.srk.android.rough1;
import java.util.ArrayList;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.app.ListActivity;
public class Rough1Activity extends ListActivity {
private ArrayList<String> listItems = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private EditText taskNameEditText;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, listItems);
setListAdapter(adapter);
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
taskNameEditText = (EditText) findViewById(R.id.TaskName);
}
public void addItems(View v) {
adapter.add(taskNameEditText.getText().toString());
}
public void deleteItems(View v) {
}
}
arraylist由带有复选框的字符串组成。使用“添加新项目”按钮添加项目。现在我的&#39; deleteItems&#39;的代码应该是什么?方法或有没有更好的方法来删除项目?
答案 0 :(得分:0)
您可以使用“删除”按钮,使用getCheckedItemPositions()和clearChoices()删除选中的行:
public void deleteItems(View v) {
ListView listView = getListView();
// Get checked row numbers
SparseBooleanArray checked = listView.getCheckedItemPositions();
// Remove row from highest to lowest index
for(int index = checked.size() - 1; index > -1; index--)
adapter.remove(adapter.getItem(checked.keyAt(index)));
// Remove checkmarks
listView.clearChoices();
}