Click和LongClick Listener抛出IllegalStateException

时间:2012-10-19 21:10:45

标签: java android exception button onclicklistener

我在尝试为onClickListener实施onLongClickListenerRelativeLayout时收到此错误:

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();

}
});

我第一次打开活动时,我可以根据需要多次进行长时间点击。但是当我点击任何其他按钮(不仅是在这里被判刑的那个)时,如果我再次尝试做一个长按...应用程序崩溃。

我将非常感谢你的帮助。 谢谢:))

1 个答案:

答案 0 :(得分:2)

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

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

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