gpt4 book ai didi

java - 单击和 LongClick 监听器抛出 IllegalStateException

转载 作者:行者123 更新时间:2023-11-30 09:31:10 26 4
gpt4 key购买 nike

我在尝试为 RelativeLayout 实现 onClickListeneronLongClickListener 时遇到此错误:

10-19 17:49:31.400: E/AndroidRuntime(30886): FATAL EXCEPTION: main
10-19 17:49:31.400: E/AndroidRuntime(30886): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

这是部分代码:

RelativeLayout meals_layout = (RelativeLayout) view
.findViewById(R.id.meals);

meals_layout.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {

AlertDialog.Builder builder = new AlertDialog.Builder(
JournalActivity.this);
builder.setTitle(R.string.meal_delete);
builder.setView(clickView);

builder.setPositiveButton(R.string.string_delete,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {

}

});
builder.setNegativeButton(R.string.string_cancel,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// Do nothing
dialog.dismiss();
}
});

builder.create().show();
return false;
}
});

meals_layout.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(
JournalActivity.this);
builder.setTitle(R.string.meal_edit); // al que hacerlo bonito
builder.setView(clickView);

builder.setPositiveButton(R.string.string_edit,
new DialogInterface.OnClickListener() {
}
});

builder.setNegativeButton(R.string.string_cancel,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// Do nothing
dialog.dismiss();
}
});


builder.create().show();

}
});

我第一次打开该 Activity 时,我可以根据需要进行多次长按。但是,当我单击任何其他按钮(不仅是此处判处的按钮)时,如果我再次尝试长按……应用程序会崩溃。

非常感谢您的帮助。谢谢:)

最佳答案

每个 View 只允许一个父 View 。显然 clickView 已经有一个,所以当您调用 setView(clickView) 时它会抛出错误。一种解决方法是添加:

((GroupView) clickView.getParent()).removeView(clickView);

到你的两个听众的开头。这将“孤立”clickView,因此可以将其添加到 AlertDialog。

关于java - 单击和 LongClick 监听器抛出 IllegalStateException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12982512/

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