如何在Android中獲取當前螢幕方向?
在某些情況下,我們需要找到Android Activity的方向。此示例演示如何整合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" android:id = "@+id/parent" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:gravity = "center" android:orientation = "vertical"> <TextView android:id = "@+id/text" android:textSize = "28sp" android:textAlignment = "center" android:layout_width = "match_parent" android:layout_height = "wrap_content" /> </LinearLayout>
在上面的程式碼中,我們使用了TextView。根據螢幕方向,TextView將更新文字。
步驟 3 - 將以下程式碼新增到src/MainActivity.java
package com.example.andy.myapplication; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; public class MainActivity extends AppCompatActivity { int view = R.layout.activity_main; TextView textview; @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(view); textview = findViewById(R.id.text); int orientation = this.getResources().getConfiguration().orientation; if (orientation = = Configuration.ORIENTATION_PORTRAIT) { textview.setText("Portrait mode"); } else { textview.setText("landscape mode"); } } }
在上面的程式碼中,我們將方向作為整數,並與配置的方向進行比較,如下所示 -
int orientation = this.getResources().getConfiguration().orientation; if (orientation = = Configuration.ORIENTATION_PORTRAIT) { textview.setText("Portrait mode"); } else { textview.setText("landscape mode"); }
讓我們嘗試執行您的應用程式。我假設您已將您的實際Android移動裝置連線到您的計算機。要從Android Studio執行應用程式,請開啟您的一個專案活動檔案,然後單擊工具欄中的執行 圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -
當用戶將手機保持為縱向模式時,它將顯示如上所示的結果。現在將裝置旋轉到橫向模式,它將顯示如下所示的結果 -
點選這裡下載專案程式碼
廣告