如何在Android运行时添加

如何在Android运行时添加

您好,我正在尝试编写一个程序,当设备在纵向模式下时可以显示一个片段,而在横向模式下则可以显示另一个片段。我遇到了一些使代码无法正常工作的问题:

我使用了getWidth()和getHeight()来获取纵向和横向模式,但是在4.3中不推荐使用这些功能,我还可以使用其他什么功能呢?

我使用了replace()函数来显示所需的片段,但由于错误而被删除

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

公共类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();
**/

}

最佳答案

尝试在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();
        }

关于android - 如何在Android运行时添加 fragment ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27877072/

10-10 16:06