我使用编辑文本框和按钮创建了自定义视图。我想通过点击一个按钮从列表视图中删除一个项目。 自定义视图代码:如何使用自定义视图中的按钮从列表视图中删除自定义视图
<?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