在更改LANDSCAPE和PORTRAIT时,片段没有正确替换

时间:2014-02-26 14:10:03

标签: android android-fragments android-fragmentactivity

我想通过使用片段改变配置更改时片段的布局..但片段在活动布局中重叠,所以请帮我解决这个问题... 和这个类文件.........

public class Self_funded_1 extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    Self_fragment ls_fragment = new Self_fragment();
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.self_funded_category);
    Configuration config = getResources().getConfiguration();

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager
            .beginTransaction();

    if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        /**
         * Landscape mode of the device
         */

        Log.i("LM", "LM");
         ls_fragment = new Self_fragment();
        fragmentTransaction.replace(android.R.id.content, ls_fragment);

    } else {
        /**
         * Portrait mode of the device
         */
        Log.i("LM", "PM");
        PM_self_funded pm_fragment = new PM_self_funded();

        fragmentTransaction.replace(android.R.id.content, pm_fragment);
        fragmentTransaction.remove(ls_fragment);
        fragmentTransaction.hide(ls_fragment);
    }
    fragmentTransaction.commit();
}

这是活动的xml文件..

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >

<fragment
    android:id="@+id/lm_fragment"
    android:name="info.com.forms.Self_fragment"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />

<fragment
    android:id="@+id/pm_fragment"
    android:name="info.com.forms.PM_self_funded"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1" />

这是快照........

enter image description here

1 个答案:

答案 0 :(得分:1)

您正在声明xml中的片段,并在Activity中进行编程。您只需选择一个选项即可。

例如,创建两个不同的布局文件,一个用于纵向,一个用于横向,并在那里声明片段,然后您不需要在活动中执行任何特殊操作。

layout/my-layout
layout-land/my-layout

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_layout);
}