簡體   English   中英

碎片和處理方向的變化

[英]fragments and handling orientation changes

我有一個帶有片段的活動。

我想自己處理方向更改,所以我更新了清單,如下所示:

    <activity android:name="com.test.app" android:configChanges="orientation|keyboardHidden"/>

然后我更新了活動,如下所示:

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        updateLayout();
    }

    private void updateLayout() {
        setContentView(R.layout.my_layout);
    }

我也用片段做到這一點:

    fragment.setRetainInstance(true);

我遇到的問題是,當我進行屏幕方向時,它在setContentView()上失敗,說我的片段有一個重復的id。 不確定如何做到這一點不會發生 - 想法?

TIA。

我相信這是因為你告訴它不要扔掉你以前的布局,所以當你旋轉它時,你仍然有你的舊視圖(在這種情況下,它與新視圖相同,因此ID沖突)。

另外,我不確定,但我認為:

fragment.setRetainInstance(true);

沒必要嗎? 因為在這里你告訴它不要重新配置你對配置更改的活動:

android:configChanges="orientation|keyboardHidden"

根據我的經驗,XML中的configChanges設置足以阻止娛樂。

編輯:

嗯,再看一遍,你究竟是如何使用Fragments的? 如果這里發布的代碼來自你的FragmentActivity,那么我希望這樣的東西可以膨脹你的Fragment並將它添加到Activity:

class SomeActivity extends FragmentActivity
{
    ...
    @Override
    public void onCreate( Bundle savedInstance )
    {
    ...
        LayoutInflater inflater = getLayoutInflater();
        inflater.inflate( R.layout.some_fragment, root );
    ...
    }
}

使用XML看起來像:some_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:name="com.someapp.fragments.SomeFragment">
</fragment>

所以我想我不清楚你是如何使用Fragments的。 但是使用它們,使用XML配置設置,成功禁用了旋轉娛樂。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM