我尝试为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();

}
});


第一次打开活动时,我可以多次进行长按。但是,当我单击其他任何按钮(不仅是此处的一个按钮)时,如果我再次尝试进行longclick操作,应用程序将崩溃。

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

最佳答案

每个视图仅允许一个父级。显然clickView已经有一个,所以当您调用setView(clickView)时,它将引发错误。一种解决方法是添加:

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


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

10-07 15:32