2

尝试同时实现onClickListener和时onLongClickListener出现此错误RelativeLayout

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

}
});

我第一次打开活动时,我可以按我想要的次数进行长按。但是,当我单击任何其他按钮时(不仅是这里所说的那个),如果我再次尝试进行长按...应用程序崩溃。

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

4

1 回答 1

2

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

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

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

于 2012-10-19T21:13:44.647 回答