Android 如何删除listview项

Android 如何删除listview项,android,Android,您好,我想检查所有listview项目,并从数据库和listview中删除这些项目。如果选择了所有listview项目,并且仅取消选中其中一个listview项目,则必须删除选中的项目。对于此iam,使用菜单。我如何实现这样的操作?Iam使用以下代码: public void PopulateSentList() { String strquery = "SELECT * FROM sent_history"; Cursor Cursor = (Mainscree

您好,我想检查所有listview项目,并从数据库和listview中删除这些项目。如果选择了所有listview项目,并且仅取消选中其中一个listview项目,则必须删除选中的项目。对于此iam,使用菜单。我如何实现这样的操作?Iam使用以下代码:

public void PopulateSentList() {
        String strquery = "SELECT * FROM sent_history";
        Cursor Cursor = (MainscreenActivity.JEEMAAndroSMSDB).rawQuery(strquery,
                null);
        MyAdapter adapter = new MyAdapter(SentHistoryActivity.this, Cursor);
        setListAdapter(adapter);        
        lvhistory.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                    int position, long arg3) {
                // TODO Auto-generated method stub
                SQLiteCursor selectedValue = (SQLiteCursor) getListAdapter()
                        .getItem(position);
                String id1 = selectedValue.getString(0);
                System.out.println("DATA-->>>" + id1);
                Intent intent = new Intent(getApplicationContext(),
                        Historydisplay.class);
                intent.putExtra("Id", id1);
                final int result = 1;
                startActivityForResult(intent, result);
            }
        });
    }

    public void onBackPressed() {
        super.onBackPressed();
        Intent intent = new Intent(SentHistoryActivity.this,
                MainscreenActivity.class);
        startActivity(intent);
        finish();
    }

    private void CreateMenu(Menu menu) {
        menu.setQwertyMode(true);
        MenuItem mnu1 = menu.add(0, 0, 0, "Delete");
        {
            mnu1.setAlphabeticShortcut('a');
        }
        MenuItem mnu2 = menu.add(1, 1, 1, "Select All");
        {
            mnu2.setAlphabeticShortcut('s');
        }
    }

    private boolean MenuChoice(MenuItem item) throws Exception {
        switch (item.getItemId()) {
        case 0:         
            if (getStrinValue != null) {
                delhistory(getStrinValue);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please select an Item", Toast.LENGTH_SHORT).show();
            }           
        case 1:
            if(item.getTitle().equals("Select All")){
                for(int i=0; i < lvhistory.getChildCount(); i++){
                    RelativeLayout itemLayout = (RelativeLayout)lvhistory.getChildAt(i);
                    final CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.check);
                    cb.setChecked(true);           
                    if (cb.isChecked() == true) {                               
                        getStrinValue = getStrinValue + ","
                                + cb.getTag().toString();
                    }
                    cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {                       
                        @Override
                        public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                            // TODO Auto-generated method stub          
                            final long[] checkedIds = lvhistory.getCheckItemIds();
                            for (int i = 0; i < checkedIds.length; i++) {
                                Log.e("checkedIds", "id checked: " + checkedIds[i]);
                            }
                            }                       
                    });                 
                }               
            }

        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        CreateMenu(menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        try {
            return MenuChoice(item);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private class MyAdapter extends ResourceCursorAdapter {

        public MyAdapter(Context context, Cursor cur) {
            super(context, R.layout.dummy, cur);
        }

        @Override
        public View newView(Context context, Cursor cur, ViewGroup parent) {
            LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            return li.inflate(R.layout.dummy, parent, false);
        }

        @Override
        public void bindView(View view, Context context, Cursor cur) {
            TextView tvListText = (TextView) view.findViewById(R.id.Mobile);
            chkBox = (CheckBox) view.findViewById(R.id.check);          
            tvListText.setText(cur.getString(cur
                    .getColumnIndex(MainscreenActivity.COL_Mobile)));
            chkBox.setTag(cur.getString(cur
                    .getColumnIndex(MainscreenActivity.COL_Sent_id)));

            chkBox.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    CheckBox cb = (CheckBox) v;
                    if (cb.isChecked() == true) {
                        getStrinValue = getStrinValue + ","
                                + cb.getTag().toString();
                    } else {
                        getStrinValue = null;
                    }
                }
            });
        }   

    }


    public void delhistory(String getStrinValue) {
        int pos1 = getStrinValue.indexOf(",");
        if (pos1 > 0) {
            String rowId = getStrinValue.substring(pos1 + 1);
            String delimiter = "\\,";
            String[] sentID = rowId.split(delimiter);
            for (int i = 0; i < sentID.length; i++) {
                String temp0 = sentID[i];
                int id = Integer.parseInt(temp0);
                MainscreenActivity.JEEMAAndroSMSDB
                        .delete(MainscreenActivity.Table_SentHistory, "_id="
                                + id, null);                
            }
            Toast.makeText(getApplicationContext(),
                    "History deleted successfully", Toast.LENGTH_SHORT)
                    .show();
            finish();
            Intent intent = new Intent(getApplicationContext(),
                    SentHistoryActivity.class);
            startActivity(intent);
        }
    }   
public void PopulateSentList(){
String strquery=“选择*来自已发送的\u历史记录”;
游标游标=(MainscreenActivity.JEEMAAndroSMSDB).rawQuery(strquery,
无效);
MyAdapter=新的MyAdapter(SentHistoryActivity.this,游标);
setListAdapter(适配器);
lvhistory.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
公共链接(AdapterView arg0、视图arg1、,
整数位置,长arg3){
//TODO自动生成的方法存根
SQLiteCursor selectedValue=(SQLiteCursor)getListAdapter()
.getItem(职位);
String id1=selectedValue.getString(0);
System.out.println(“数据-->>>”+id1);
意向意向=新意向(getApplicationContext(),
历史显示类);
意向。额外(“Id”,id1);
最终int结果=1;
startActivityForResult(意图、结果);
}
});
}
public void onBackPressed(){
super.onBackPressed();
意向意向=新意向(SentHistoryActivity.this,
活动类);
星触觉(意向);
完成();
}
私有void CreateMenu(菜单菜单){
menu.setQwertyMode(true);
MenuItem mnu1=菜单。添加(0,0,0,“删除”);
{
mnu1.设置字母短切('a');
}
MenuItem mnu2=菜单。添加(1,1,1,“全选”);
{
mnu2.setalphalcshortcut('s');
}
}
私有布尔MenuChoice(MenuItem项)引发异常{
开关(item.getItemId()){
案例0:
if(getStrinValue!=null){
delhistory(getStrinValue);
}否则{
Toast.makeText(getApplicationContext(),
“请选择一个项目”,Toast.LENGTH_SHORT.show();
}           
案例1:
if(item.getTitle().equals(“全选”)){
for(int i=0;i0){
String rowId=getStrinValue.substring(pos1+1);
字符串分隔符=“\\,”;
字符串[]sentID=rowId.split(分隔符);
for(int i=0;i<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText 
        android:id="@+id/txtItem"
        android:layout_width="240dp"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:hint="@string/hintTxtItem"         
        />

    <Button 
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/lblBtnAdd"
        android:layout_toRightOf="@id/txtItem"
        />

    <TextView 
        android:id="@android:id/empty"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtItem"
        android:text="@string/txtEmpty"
        android:gravity="center_horizontal"        
        />

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"        
        android:layout_below="@id/txtItem"
        android:choiceMode="multipleChoice" >
    </ListView>

    <Button
        android:id="@+id/btnDel"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"        
        android:layout_alignParentBottom="true"
        android:text="@string/lblBtnDel" />


</RelativeLayout>
public class MainActivity extends ListActivity {

    /** Items entered by the user is stored in this ArrayList variable */
    ArrayList<String> list = new ArrayList<String>();

    /** Declaring an ArrayAdapter to set items to ListView */
    ArrayAdapter<String> adapter;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        /** Setting a custom layout for the list activity */
        setContentView(R.layout.main);

        /** Reference to the add button of the layout main.xml */
        Button btn = (Button) findViewById(R.id.btnAdd);

        /** Reference to the delete button of the layout main.xml */
        Button btnDel = (Button) findViewById(R.id.btnDel);

        /** Defining the ArrayAdapter to set items to ListView */
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, list);

        /** Defining a click event listener for the button "Add" */
        OnClickListener listener = new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                                EditText edit = (EditText) findViewById(R.id.txtItem);
                                list.add(edit.getText().toString());
                                edit.setText("");
                                adapter.notifyDataSetChanged();
                        }
                };

        /** Defining a click event listener for the button "Delete" */
        OnClickListener listenerDel = new OnClickListener() {
            @Override
            public void onClick(View v) {
                /** Getting the checked items from the listview */
                SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
                int itemCount = getListView().getCount();

                for(int i=itemCount-1; i >= 0; i--){
                    if(checkedItemPositions.get(i)){                        
                        adapter.remove(list.get(i));
                    }
                }               
                adapter.notifyDataSetChanged();             
            }
        };            

        /** Setting the event listener for the add button */
        btn.setOnClickListener(listener);

        /** Setting the event listener for the delete button */
        btnDel.setOnClickListener(listenerDel);    

        /** Setting the adapter to the ListView */
        setListAdapter(adapter);
    }
}
   adapter.remove(list.get(i));
adapter.notifyDatasetChanged()