如何在 Android 應用程式中忽略螢幕方向變更?


本示例演示如何在 Android 中使應用程式忽略螢幕方向更改。

步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新專案,並填寫所有必填項以建立一個新專案。

步驟 2 − 將以下程式碼新增到 res/layout/activity_main.xml 中。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Hello World!"
   app:layout_constraintBottom_toBottomOf="parent"
   app:layout_constraintLeft_toLeftOf="parent"
   app:layout_constraintRight_toRightOf="parent"
   app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

步驟 3 − 將以下程式碼新增到 src/MainActivity.java 中

package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
   }
}

步驟 4 − 將以下程式碼新增到 Manifests/AndroidManifest.xml 中

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.app.sample">
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      <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">
            <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
         </activity>
   </application>
</manifest>

讓我們試著執行你的應用程式。我假設你已將你的實際 Android 移動裝置與你的計算機連線。要從安卓工作室執行該應用程式,請開啟你的其中一個專案的活動檔案,然後單擊工具欄上的執行播放圖示 圖示。選擇你的移動裝置為選項,然後檢查你的移動裝置,它將顯示你的預設螢幕 −

更新日期: 07-Jul-2020

320 次瀏覽

開始你的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.