android 如何在运行时添加片段

How to add fragment during runtime in android

你好,我正在尝试编写一个程序,当设备处于纵向模式时可以显示一个片段,而当设备处于横向模式时可以显示另一个片段。我遇到了一些导致代码无法运行的问题:

我使用了 getWidth() 和 getHeight() 来获取纵向和横向模式,但是这些函数在 4.3 中已弃用,我还可以使用哪些其他函数来执行此操作?

我使用了replace()函数显示了我想要的片段,但是被错误删除了

完整代码如下。您会发现我已经使用箭头和注释指出错误的位置,因此您会确切地知道我的代码中的问题所在。请查看我的代码并帮助我修复它。

public class MainActivity 扩展了 ActionBarActivity {

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


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

    //---get the current display info---
    WindowManager wm = getWindowManager();
    Display d = wm.getDefaultDisplay();

    if (d.getWidth() > d.getHeight())//<----------these two functions get struck out as //an error
    {
    //---landscape mode---
        Fragment1 fragment1 = new Fragment1();
        // android.R.id.content refers to the content
        // view of the activity
        fragmentTransaction.replace( //<------this replace() function is seen as an //error
                android.R.id.content, fragment1);
        }
    else
    {
    //---portrait mode---
    Fragment2 fragment2 = new Fragment2();
    fragmentTransaction.replace(//<------this replace() function is also seen as an //error
            android.R.id.content, fragment2);

    }
    fragmentTransaction.commit();
**/

}

您可以通过覆盖 activity 中的 onConfigurationChanged() 方法来检查实际屏幕方向。

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        //load landscape fragment
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        //load portrait fragment
    }
}

同样可以做到onCreate()。可以使用

调用您的配置
Configuration config = getResources().getConfiguration();

也请看一下 here,因为您可能需要稍微编辑一下清单文件。对于 activity 处理方向变化,您需要设置:

<activity android:name=".MyActivity"
          android:configChanges="orientation"
          ... >

尝试在您的 onCreate 中使用这样的模式。它更简洁,而且它使用正确的 getSupportFragmentManager() 而不是继承的、有限的 getFragmentManager():

    int currentOrientation = getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE)
        {

            Fragment1 placeholder = new Fragment1();
            placeholder.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, placeholder).commit();
        } else
        {
            Fragment2 placeholder = new Fragment2();
            placeholder.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container, placeholder).commit();
        }

创建两个 Activity 布局,但为它们指定完全相同的名称(示例 activity_main.xml)。

将一个放在您的 res/layout-port 目录中...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

</LinearLayout>

将另一个放在 res/layout-land 目录中...

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

</LinearLayout>

请注意 FrameLayouts 具有不同的资源 ID(@+id/container-port@+id/container-land)。

在您的 MainActivity 中,只需使用如下代码...

public class MainActivity extends ActionBarActivity {

    FrameLayout container;
    boolean isPortrait = true

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

        container = (FrameLayout) findViewById(R.id.container-port);
        if (container == null) {
            isPortrait = false;
            container = (FrameLayout) findViewById(R.id.container-land);
        }

        ...

     }
}

Android 将根据设备的方向自动膨胀相关布局。无需获取宽度/高度,甚至无需直接检查方向。这是通过尝试使用 findViewById(...) 并根据容器是否为 null 相应地设置布尔值来隐式完成的。从那时起,您可以使用 isPortrait 布尔值来指示代码的工作方式。

此外,如果您使用的是支持库,N8sBug 关于使用 getSupportFragmentManager() 是正确的。