[英]Android - Delete item from ListActivity onClick?
我有一個帶有文本Delete
的按鈕,它位於創建的列表項的旁邊,我希望它能夠在單擊按鈕時刪除其列表項。 但是在實施時,我發現引用哪個列表項將被刪除以及列表項不再可編輯時出錯。 如何在代碼中引用被單擊時要刪除的項目以及如何再次使列表項目可用? 感謝您的所有回復!
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++)
{
lvItems.getChildAt(i).setBackgroundColor(Color.GREEN);
}
LinearLayout vwParentRow = (LinearLayout)v.getParent();
Button Delbtn = (Button)vwParentRow.getChildAt(1);
}
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();
}
}
函數MyClickHandler
是我已將按鈕的onClick
設置為XML內的函數
<Button
android:id="@+id/Delbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="right"
android:text="Delete"
android:onClick="myClickHandler" />
因此,您要做的是在列表視圖中向列表項添加一個按鈕。 在這里,我學會了如何做。 http://androidforbeginners.blogspot.in/2010/03/clicking-buttons-in-listview-row.html
希望能幫助到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.