如何在Android中停用橫屏模式?
Android支援兩種方向:縱向和橫向。我們可以在Android應用程式中停用方向。此示例演示如何在Android中停用橫向模式。
步驟 1 - 在Android Studio中建立一個新專案,轉到檔案⇒新建專案,並填寫所有必要的資訊以建立新專案。
步驟 2 - 將以下程式碼新增到res/layout/activity_main.xml。
<?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:background = "#dde4dd"> <EditText android:id = "@+id/editText" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout>
在上面的程式碼中,它包含線性佈局和EditText。它將支援橫向和縱向,如下所示 -
以上輸出表示橫向模式
以上輸出表示縱向模式。
要停用橫向模式,需要在manifest.xml中新增screenOrientation標籤,如下所示 -
<?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.andy.myapplication"> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity" android:screenOrientation = "portrait"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
在上面的程式碼中,我們將screenOrientation設定為縱向,這意味著MainActivity將只支援縱向模式。如果您想開發一個縱向模式的應用程式,請在application標籤內新增screenOrientation。
讓我們嘗試執行您的應用程式。我假設您已將您的實際Android手機裝置連線到您的電腦。要從Android Studio執行應用程式,請開啟您的專案中的一個Activity檔案,然後單擊工具欄中的執行 圖示。選擇您的手機裝置作為選項,然後檢查您的手機裝置,它將顯示您的預設螢幕 -
在以上結果中,它只顯示縱向模式。現在旋轉您的裝置,它不會根據方向更改檢視。
廣告