gpt4 book ai didi

android - 无法将参数传递给 OnClickListener?

转载 作者:行者123 更新时间:2023-11-29 15:02:44 25 4
gpt4 key购买 nike

我有我的 Activity 适配器来处理我的主要项目列表。当我点击删除时,我想提示用户,如果确认从列表中删除该项目并刷新 View 。

我有删除项目的逻辑,但似乎没有办法将参数传递给 OnClickListener。如果我单击列表上的按钮,如何捕获单击的位置以及如何将其传递给 OnClickListener 函数以便删除正确的元素?

如有任何帮助,我们将不胜感激

谢谢,拉德克

 @Override
public View getView(final int _position, View convertView, ViewGroup parent) {

try {
if(convertView == null){
convertView = layoutInflater.inflate(com.mylist.www.R.layout.activity_main_row,parent,false);
}

TextView textView = (TextView) convertView.findViewById(com.mylist.www.R.id.rowText);
textView.setText(listItems.getJSONObject(_position).getString("description"));

// set the checkbox stuff
CheckBox chkEnabled = (CheckBox) convertView.findViewById(com.mylist.www.R.id.chkEnabled);

textView.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
try{
if (listItems != null){
JSONArray clickedItems = listItems.getJSONObject(_position).getJSONArray("listItems"); // position
Intent intent = new Intent(context, ListActivity.class);

intent.putExtra("listItems", clickedItems.toString());
context.startActivity(intent);
}
} catch (Exception e){
e.printStackTrace();
}

}

});

Button btnNavigate = (Button) convertView.findViewById(com.mylist.www.R.id.btnDelete);
btnNavigate.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
try{
if (listItems != null){

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
}
} catch (Exception e){
e.printStackTrace();
}

}

});


return convertView;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {

try {
switch (which){
case DialogInterface.BUTTON_POSITIVE:
//Yes button clicked
listItems.remove(position); //????? how do I pass it

JSONObject jObj = new JSONObject();
jObj.put("Items", listItems);

editor.putString("json",jObj.toString());
editor.commit();

((MainActivity)context).refreshView();

break;

case DialogInterface.BUTTON_NEGATIVE:
//No button clicked
break;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};

最佳答案

为什么不将位置存储在另一个变量中并在以后使用它

int currentPosition;

当用户单击按钮时,将当前 View 位置存储在 getView()

currentPosition = position;

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();

然后在你的监听器中使用它

listItems.remove(currentPosition);

关于android - 无法将参数传递给 OnClickListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41950046/

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