簡體   English   中英

屏幕方向改變碎片

[英]Screen orientation change on fragments

我需要檢測片段上的屏幕方向變化,並且要這樣做,我目前正在使用此方法:

public void onEvent(OrientationEvent event){...}

在Nexus 4上可以正常使用。我的問題是在Samsung Galaxy S3上,旋轉屏幕時未調用該方法。 有人有主意嗎?

非常感謝。

關於此@ 處理運行時更改,有一個不錯的Google網頁。 這涵蓋了用戶在水平/垂直視圖之間切換屏幕以及切換應用程序的時間。 程式碼片段:

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

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

上面的代碼可以放在Activity或Fragment子類中。

在清單xml中,設置:

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

請隨時向我們發布消息,我想知道您的進度。 有一天我可能也想這樣做。 如果我願意的話,我會這樣編碼

private String getScreenOrientation(){    
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
    return "ORIENTATION_PORTRAIT";
else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
    return "ORIENTATION_LANDSCAPE";
else
    return "";

}

您需要在片段中簡單地重寫onConfigurationChange()方法。 您可以看一下這個開發人員的android帖子:

公共無效onConfigurationChanged(配置newConfig)

組件運行 時設備配置發生更改時,系統調用此方法 請注意,與活動不同,其他組件永遠不會在配置更改時重新啟動:它們必須始終處理更改的結果,例如通過重新獲取資源。

調用此函數時,您的Resources對象將被更新以返回與新配置匹配的資源值。

參數

newConfig新設備配置。

在onConfigurationChanged內部,您需要檢查當前方向,例如:

newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE
newConfig.orientation == Configuration.ORIENTATION_PORTRAIT

並添加邏輯

暫無
暫無

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

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