Android:如何防止在方向更改时清除类变量

时间:2016-05-08 23:39:28

标签: java android user-interface fragment android-orientation

我有一个主要的活动有两个配置,一个会显示一个锁定为纵向的片段。

当在此片段上单击一个按钮时,片段会替换它,但是这个新片段可以与第二个片段并排显示。

这一切都运行正常,但我在第二个状态拦截反向导航,以便我可以用原始配置替换片段。更改方向时,我的所有类变量都将被重置,并且我对片段的引用将丢失。

以下是主要活动:

package mobileapp.group2.fragmenttest;

import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

public class MainActivity extends FragmentActivity
    implements ListPeersFragment.ListPeersFragmentListener
{
    public static final String LIST_FRAGMENT_TAG = "ListPeersFragment";
    public static final String GAME_FRAGMENT_TAG = "GameFragment";
    public static final String OPP_FRAGMENT_TAG  = "ViewOpponentFragment";

    // FrameLayout references
    private FrameLayout mLeftFrame;
    private FrameLayout mRightFrame;

    // Fragment references
    private ListPeersFragment mListPeersFragment = null;
    private GameFragment      mGameFragment      = null;
    private ViewOppFragment   mViewOppFragment   = null;

    // Boolean denoting if currently in game mode.
    //private boolean mGameMode;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLeftFrame  = (FrameLayout) findViewById(R.id.left_frame);
        mRightFrame = (FrameLayout) findViewById(R.id.right_frame);

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create fragments
        if (mListPeersFragment == null)
            mListPeersFragment = new ListPeersFragment();
        if (mGameFragment == null)
            mGameFragment    = new GameFragment();
        if (mViewOppFragment == null)
            mViewOppFragment = new ViewOppFragment();

        // In case this activity was started with special instructions from an
        // Intent, pass the Intent's extras to the fragment as arguments
        mListPeersFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        FragmentManager fm = getSupportFragmentManager();
        fm.beginTransaction().add(R.id.left_frame, mListPeersFragment, LIST_FRAGMENT_TAG).commit();
        fm.beginTransaction().add(R.id.right_frame, mViewOppFragment, OPP_FRAGMENT_TAG).commit();

        //mGameMode = false;
    }

    // Used to intercept back navigation.
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            FragmentManager fm = getSupportFragmentManager();
            if (fm.findFragmentByTag(GAME_FRAGMENT_TAG) != null)
            {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                //FragmentTransaction ft = fm.beginTransaction();
                fm.beginTransaction().replace(R.id.left_frame, mListPeersFragment, LIST_FRAGMENT_TAG)
                        .commitAllowingStateLoss();
                //mGameMode = false;
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void startGame()
    {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.left_frame, mGameFragment, GAME_FRAGMENT_TAG).commit();

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        //mGameMode = true;
    }

    // Implementation of the ListPeersFragmentListener function onPeerSelected
    public void onPeerSelected(int position)
    {

    }

}

主要活动布局文件:

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

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 android:id="@+id/left_frame"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"/>

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
                 android:id="@+id/right_frame"
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"/>

</LinearLayout>

横向版本在framelayouts上只有权重。

其他片段类非常简单,他们现在什么都不做。

失败的代码是onKeyDown方法。有没有办法防止类变量在方向更改时重新初始化?我已经查看了处理配置更改但是未加载横向布局文件。

如果有人能提供帮助,我们将非常感激!

2 个答案:

答案 0 :(得分:1)

您应该使用this link中提到的活动的onSaveInstanceState()onRestoreInstanceState()方法。

此外,您需要调用要保存的片段中的setRetainInstance()方法。

有关setRetainInstanceState()的详细信息,请查看this link

答案 1 :(得分:0)

实际上,无论何时更改方向,都会调用活动Oncreate()方法。因此,为了防止清除变量,重写OnConfigurationChange()方法并在清单文件中执行以下操作: -

android:configChanges="orientation"
相关问题