如何在縱向模式下檢查活動?


本示例演示瞭如何在縱向模式下檢查活動。

第 1 步 − 在 Android Studio 中建立新專案,轉到檔案 ⇒ 新專案並填寫所有必需詳細資訊以建立新專案。

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

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:id="@+id/conf"
      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" />
</android.support.constraint.ConstraintLayout>

在以上程式碼中,我們採用了文字檢視來顯示模式名稱。

第 3 步− 將以下程式碼新增到 java/MainActivity.xml

package com.example.myapplication;

import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   TextView conf;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      conf = findViewById(R.id.conf);
   }
   @Override
   public void onConfigurationChanged(Configuration _newConfig) {
      super.onConfigurationChanged(_newConfig);
      if (_newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
         conf.setText("It is landscape");
      } else {
         conf.setText("It is portrait mode");
      }
   }
}

第 3 步− 將以下程式碼新增到 AndroidManifest.xml

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

讓我們嘗試執行你的應用程式。我假設你已將你的實際 Android 移動裝置連線到了你的計算機。要從 Android Studio 執行應用程式,請開啟你的一個專案的活動檔案,然後單擊工具欄中的執行  圖示。選擇你的移動裝置作為選項,然後檢查你的移動裝置,它將顯示你的預設螢幕 –

點選 此處 下載專案程式碼

更新於:2020 年 6 月 26 日

153 次瀏覽

點亮您的 職業

完成課程認證

開始學習
廣告
© . All rights reserved.