我使用編輯文本框和按鈕創建了自定義視圖。我想通過點擊一個按鈕從列表視圖中刪除一個項目。 自定義視圖代碼:如何使用自定義視圖中的按鈕從列表視圖中刪除自定義視圖
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete"
android:id="@+id/delete_btn"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/player_name_txt"
android:textColor="#ffffff"
android:editable="false"
android:background="#5eb8ed"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="@+id/delete_btn"
android:layout_toLeftOf="@+id/delete_btn"
android:layout_toStartOf="@+id/delete_btn" />
</RelativeLayout>
該適配器和列表視圖代碼:
inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
playerListView = (ListView)this.findViewById(android.R.id.content).getRootView().findViewById(R.id.player_list);
playerListAdapter = new ArrayAdapter(this,R.layout.player_item,R.id.player_name_txt, new ArrayList<String>(){});
playerListView.setAdapter(playerListAdapter);
代碼中,我嘗試:
public void removePlayer(View v)
{
EditText pairedEdit = (EditText)findViewById(R.id.player_name_txt);
String name = pairedEdit.getText().toString();
playerListAdapter.remove(name);
playerListAdapter.notifyDataSetChanged();
}
現在它消除了第一項在列表視圖中。
AlertDialog.Builder addPlayerBuilder = new AlertDialog.Builder(this);
final View customView = inflater.inflate(R.layout.add_player,null);
final EditText usernameEdit = (EditText)customView.findViewById(R.id.username_edit);
addPlayerBuilder.setView(customView);
addPlayerBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String name = usernameEdit.getText().toString();
playerListAdapter.add(name);
playerListAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
addPlayerBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = addPlayerBuilder.create();
dialog.show();
你需要它的位置刪除所選項目 –
你可以給這兩個元素標籤各自的resoure ID作爲鍵和刪除其他元素,當按鈕被添加onclick屬性或onclicklistener點擊。將可見性設置爲消失或不可見。 – Bob