簡體   English   中英

Android-刪除ListActivity中的項目

[英]Android - Delete item within ListActivity

我的ListActivity類中的每個列表項旁邊都有一個Delete按鈕,而在Delete按鈕中,我有android:onClick="myClickHandler" 現在,我正在處理myClickHandler函數中的代碼,以成功刪除所選列表項。 有人可以給我一些建議,告訴我如何在我的代碼中引用要刪除的項目以及在單擊該項目時將其刪除嗎? 我已經提供了ListActivity代碼。感謝您的所有回復!

public class LyricList extends ListActivity {

private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private LyricsDbAdapter mDbHelper;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_lyriclist);
    mDbHelper = new LyricsDbAdapter(this);
    mDbHelper.open();
    fillData();
    registerForContextMenu(getListView());
}

private void fillData() {
    Cursor lyricsCursor = mDbHelper.fetchAllLyrics();
    startManagingCursor(lyricsCursor);
    String[] from = new String[]{LyricsDbAdapter.KEY_TITLE};
    int[] to = new int[]{R.id.text1};
    SimpleCursorAdapter lyrics = 
        new SimpleCursorAdapter(this, R.layout.lyrics_row, lyricsCursor, from, to);
    setListAdapter(lyrics);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    menu.add(0, INSERT_ID, 0, R.string.menu_insert);
    return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch(item.getItemId()) {
        case INSERT_ID:
            createLyric();
            return true;
    }

    return super.onMenuItemSelected(featureId, item);
}

public void myClickHandler(View v) 
{
    ListView lvItems = getListView();
    for (int i=0; i < lvItems.getChildCount(); i++) 
    {
        //incorrectly implemented...getting errors within this
        LinearLayout vwParentRow = (LinearLayout)v.getParent();
        Button Delbtn = (Button)vwParentRow.getChildAt(1);
        DELETE_ID:
        mDbHelper.deleteLyric(lvItems.getChildAt(i)); 

    }

}

private void createLyric() {
    Intent i = new Intent(this, NextActivity.class);
    startActivityForResult(i, ACTIVITY_CREATE);
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Intent i = new Intent(this, NextActivity.class);
    i.putExtra(LyricsDbAdapter.KEY_ROWID, id);
    startActivityForResult(i, ACTIVITY_EDIT);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    fillData();
}
}

你需要

  1. 從數據庫中刪除它。
  2. 在游標上調用requery()。
  3. 在適配器上調用notifyDataSetChanged。

編輯:為了獲得ID,您應該覆蓋適配器的bindView函數,並在其中附加OnClickListener。

如何使用CursorAdapter從ListView中刪除選定的項目

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM