如何使用 Kotlin 在 Android 中檢測佈局中的方向更改?


步驟 1 − 在 Android Studio 中建立一個新專案,依次轉到檔案 ⇒ 新專案,然後填寫所有必需的詳細資訊來建立新專案。

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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_centerHorizontal="true"
      android:layout_marginTop="50dp"
      android:text="Tutorials Point"
      android:textAlignment="center"
      android:textColor="@android:color/holo_green_dark"
      android:textSize="32sp"
      android:textStyle="bold" />
   <TextView
      android:layout_centerInParent="true"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Hello World!"
      android:textSize="24sp"
      android:textStyle="bold" />
</RelativeLayout>

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

import android.content.res.Configuration
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
   }
   override fun onConfigurationChanged(newConfig: Configuration) {
      super.onConfigurationChanged(newConfig)
      if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
         Toast.makeText(baseContext, "Landscape Mode", Toast.LENGTH_SHORT).show()
      } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
         Toast.makeText(baseContext, "Portrait Mode", Toast.LENGTH_SHORT).show()
      }
   }
}

步驟 4 − 將以下程式碼新增到 androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.q11">
   <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 移動裝置連線到了你的計算機。要從 Android Studio 執行該應用程式,請開啟你的一個專案活動檔案並單擊工具欄中的執行圖示 。選擇你的移動裝置作為選項,然後檢查你的移動裝置,它將顯示你的預設螢幕


05-11-2020 更新

955 次瀏覽

開啟您的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.