首页 > 解决方案 > 片段中的 Android 视图重叠

问题描述

所以我已经阅读了几个教程和许多关于 SO 的帖子,但我仍然无法让它工作。我正在尝试使用动态添加的片段,但是当在片段中加载片段时,TextViews 和 ImageViews 保持重叠而不是更新它们的值,如下所示: 在此处输入图像描述

和片段在替换时相互重叠。

我有一个主要活动(扩展 AppCompatActivity)分为 2 个布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/root_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background_white"
android:orientation="vertical"
tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/upperFrameLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" />

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/lowerLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
...

上部 FrameLayout 包含我的片段。片段在 MainActivity 类的这个方法中被替换:

void setMode() {
    // Show "find opponent"- or "fight"-fragment
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

    if (!debugFight && (btCoordinator == null || !btCoordinator.isConnected())) {
        fragmentTransaction.replace(R.id.upperFrameLayout, new FindOpponentFragment());
    } else {
        fragmentTransaction.replace(R.id.upperFrameLayout, new FightFragment());
    }
    fragmentTransaction.commitNow();
}

我错过了什么?

编辑:添加了 FightFragment onCreateView() 方法:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    ((TextView) inflater.inflate(R.layout.fragment_fight, container, false).findViewById(R.id.score_textView)).setText(getString(R.string.score, 0, 0));
    ((TextView) inflater.inflate(R.layout.fragment_fight, container, false).findViewById(R.id.opponent_textView)).setText(MainActivity.opponentName.toUpperCase());

    final AnimatedVectorDrawableCompat animated = AnimatedVectorDrawableCompat.create(container.getContext(), R.drawable.loading_animated_vector);
    animated.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
        @Override
        public void onAnimationEnd(Drawable drawable) {
            animated.start();
        }
    });
    ((ImageView) inflater.inflate(R.layout.fragment_fight, container, false).findViewById(R.id.opponent_hand_imageview)).setImageDrawable(animated);
    animated.start();

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_fight, container, false);
}

...当我粘贴这段代码时,我才意识到那些膨胀的视图都是不同的对象。我用我修改的单个对象替换它们,然后让方法返回并且它可以工作。我想我必须阅读视图和膨胀方法。

标签: androidandroid-fragmentsandroid-activity

解决方案


我不明白如何充气方法。我修改了我在 OP 中看到的 onCreateView 方法的片段,现在它可以工作了。


推荐阅读