【问题标题】:Android Fragment's view is duplicated on Activity RecreationAndroid Fragment 的视图在 Activity Recreation 上重复
【发布时间】:2016-11-12 00:18:48
【问题描述】:

当一个 Activity 生成一个 Fragment 并在稍后重新创建时(例如,通过旋转屏幕),与该 Fragment 关联的视图将被复制,当该 Fragment 稍后被销毁时,只有一个被销毁。

当且仅当 Activity 直接在其 onSaveInstanceState 覆盖或不覆盖回调时调用 super.onSaveInstanceState 时才会发生这种情况。

重现的最少代码: MainActivity.java:

package com.example.trevor.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;

/**
 * Created by trevor on 11/11/16.
 */

public class MainActivity extends Activity {
    MainFragment fragment = new MainFragment();
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CheckBox checkbox = (CheckBox)findViewById(R.id.checkBox);
        checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b)
                {
                    getFragmentManager().beginTransaction().add(R.id.container,fragment).commit();
                }
                else
                {
                    getFragmentManager().beginTransaction().remove(fragment).commit();
                }
            }
        });
    }
}

MainFragment.java:

package com.example.trevor.test;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by trevor on 11/11/16.
 */

public class MainFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return inflater.inflate(R.layout.fragment_main,container,false);
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <CheckBox
        android:text="CheckBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/checkBox" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container">

    </FrameLayout>
</LinearLayout>

fragment_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:text="Open"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />
</LinearLayout>

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.trevor.test">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

    </application>

</manifest>

预期行为:选中该框会导致“打开”一词出现在下方。取消选中会导致单词消失。

实际行为:选中该框会使“打开”一词出现在下方。如果随后旋转屏幕,“open”一词会变暗,取消选中该框会使该词变为正常阴影。

【问题讨论】:

    标签: android android-fragments


    【解决方案1】:

    您最初添加的Fragment 会在Activity 重新创建时自动恢复。这是Fragments 的标准行为。此外,CheckBox 的检查状态在Activity 重新创建后恢复,因此其onCheckedChanged() 方法再次触发,并加载Fragment 的另一个实例。如果您在选中CheckBox 的情况下继续更改方向,那么越来越多的Fragment 实例将不断堆积。您需要在添加之前检查Fragment 实例是否已存在。

    由于Fragment 将自动重新添加,在OnCheckedChangeListener 中添加和删除它会很麻烦,因为您首先需要检查它是否附加到FragmentManager,并且然后确定它是否正在显示。在确保实例化和添加之后,根据需要只使用 hide()show() 可能会更简单。

    例如:

    fragment = (MainFragment) getFragmentManager().findFragmentById(R.id.container);
    
    checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if(b)
            {
                if(fragment == null) {
                    fragment = new MainFragment();
                    getFragmentManager().beginTransaction().add(R.id.container, fragment).commit();
                }
                else {
                    getFragmentManager().beginTransaction().show(fragment).commit();
                }
            }
            else
            {
                if (fragment != null) {
                    getFragmentManager().beginTransaction().hide(fragment).commit();
                }
            }
        }
    });
    

    然后您可以从MainFragment 的声明中删除初始化。

    MainFragment fragment;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-23
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-14
      相关资源
      最近更新 更多