屏幕旋转后奇怪的消失片段

时间:2014-08-13 20:03:08

标签: android android-fragments rotation

是我还是Android真的很奇怪?对不起,这不是我的问题..

我有一个简单的类,我写了练习使用片段。实例化两个不同颜色的片段,然后按下按钮以在它们之间切换。它完美无缺 - 只要我不旋转手机。我可以无休止地来回切换,使碎片来回切换。但是,如果我旋转 - 比如从陆地到港口,那么我只能在两个碎片消失之前切换3次,留下一个空容器。    看起来很奇怪,在旋转之后我又在它休息之前得到3个 - 我找不到任何押韵也没有理由。 ---澄清我旋转一次并且很好但是在我按下交换按钮3次之后它只是进入一个空白屏幕,这是我假设我的空容器。

这是我的代码:

package self.redway.dynamicfragment;

import android.app.Activity;
import android.os.Bundle;

import android.view.View;

public class MainActivity extends Activity
{
    private FragmentOne frag1;
    private FragmentTwo frag2;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        frag1 = new FragmentOne();
        frag2 = new FragmentTwo();

        getFragmentManager().beginTransaction().add(R.id.layout1, frag1).commit();
    }

    public void callFrag2(View v)
    {
        getFragmentManager().beginTransaction().replace(R.id.layout1, frag2).commit();
    }

    public void callFrag1(View v)
    {   
        getFragmentManager().beginTransaction().replace(R.id.layout1, frag1).commit();
    }
}

FragmentOne的代码(实际上与FragmentTwo完全相同):

package self.redway.dynamicfragment;

import android.app.Fragment;
import android.os.Bundle;

import android.view.View;
import android.view.LayoutInflater;
import android.view.ViewGroup;

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

我尝试添加一个空构造函数(没有区别)。我想如果我实际上做了两个单独的布局 - 一个用于端口,一个用于可能有用的土地。我还没有尝试过。但即使这样有用,我也很想知道为什么以及地球是怎么回事????

这是frag_one的布局代码,它与frag_2只是一个不同的颜色相同:

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="22sp"
        android:text="Hi I am fragment one giving my message. Please press the button to cycle to next Frag."
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press Me"
        android:onClick="callFrag2"
        />

</LinearLayout>

主要布局实际上只是一个空布局,其唯一目的是动态保存片段。

0 个答案:

没有答案
相关问题