android - 试图从一个布局中删除 View 并添加到另一个布局

标签 android android-layout

我正在尝试修改 CheckBox 单击操作的布局。

检查操作正常,但取消检查会出错:

java.lang.IllegalStateException: The specified child already has a
parent. You must call removeView() on the child's parent first.

这是我的代码:

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        presenter.onCukRulesClicked();

        final LinearLayout checkboxesContainer = (LinearLayout) findViewById(R.id.checkboxes_container);

        final LinearLayout rootView = (LinearLayout) findViewById(R.id.linearLayout2345);

        final LinearLayout leftContainer = (LinearLayout) findViewById(R.id.left_container);

        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            if (isChecked) {
                leftContainer.removeView(checkboxesContainer);
                leftContainer.invalidate();
                rootView.addView(checkboxesContainer);
            } else {
                rootView.removeView(checkboxesContainer);
                rootView.invalidate();
                leftContainer.addView(checkboxesContainer);
            }
    }

我做错了什么?

最佳答案

Android 转换造成的 removeView(view) Action 延迟存在问题。它只发生在较新的 Android 系统版本设备上。

解决方案非常简单。我没有使用 invalidate() View ,而是使用 rootView.setLayoutTransition(null) 删除了转换。

代码如下:

 if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
            if (isChecked) {
                leftContainer.removeView(checkboxesContainer);
                rootView.addView(checkboxesContainer);
            } else {
                rootView.setLayoutTransition(null);
                rootView.removeView(checkboxesContainer);
                leftContainer.addView(checkboxesContainer);
            }

关于android - 试图从一个布局中删除 View 并添加到另一个布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41218172/

相关文章:

android - 如何在没有 fragment 的情况下使用抽屉导航?

android - 在 Canvas 上绘制透明形状

android - 重新创建 Twitter 的滑入/滑出 Activity 动画

android - 使 LinearLayout 像按钮一样

java - Android 截击 : Headers are not appended

android - AccessibilityNodeInfo - 发送文本

android - C代码编译不正确

android - 如何在Android中定义 "inflation"

java - 在 Android 中动画旋转图像

android - 如何让用户选择背景颜色