gpt4 book ai didi

java - 从 ListView 中删除元素(滑动或单击)

转载 作者:行者123 更新时间:2023-12-01 17:20:13 25 4
gpt4 key购买 nike

我正在尝试创建一个动态 ListView 。我可以添加一个项目,但现在无法删除它。代码实际上非常简单,我看到的每个指南对我和我的代码来说都太复杂了。我想要在我的 MainActivity 中添加一些简单的内容来删除选定的项目。我不在乎以哪种方式,像 gmail 一样滑动或通过单击或任何其他方式。我只想要简单的方法来删除列表中的元素。这是 Activity

public class MainActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();

}

private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.addbtn);
lvItem = (ListView)this.findViewById(R.id.listView_items);


itemArrey = new ArrayList<String>();
itemArrey.clear();

itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);


btnAdd.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

addItemList();
}
});

etInput.setOnKeyListener(new View.OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub

if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});


}

protected void addItemList() {

if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");

itemAdapter.notifyDataSetChanged();

}

}

protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Insert a value");
return false;
} else {
return true;
}

}
}

是否可以插入代码的某些部分来删除我的 Activity 代码中的项目?谢谢

最佳答案

试试这个,当 ListView 项目长 ClickListener 时你可以做到

 lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {

@Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(
YourActivity.this);
adb.setTitle("Are you sure want to delete this item");
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();


}
});
adb.setNegativeButton("NO",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();

}
});
adb.show();

return false;
}
});

关于java - 从 ListView 中删除元素(滑动或单击),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19290952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com