如何以程式設計的方式獲取 Android 導航欄的高度和寬度?
本示例演示如何以程式設計方式獲取 Android 導航欄的高度和寬度。
步驟 1 − 在 Android Studio 中建立一個新專案,進入 File ⇒ New Project 填寫所有必要資訊建立新專案。
步驟 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" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Android Navigation Bar Height and Width" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="24sp" android:textStyle="bold" /> </LinearLayout>
步驟 3 − 向 src/MainActivity.java 新增以下程式碼
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
Resources resources = getApplicationContext().getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
textView.setText(resourceId);
}
}
}
步驟 4 − 向 androidManifest.xml 新增以下程式碼
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <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 執行應用程式,請開啟你的一個專案活動檔案,然後單擊工具欄中的執行
圖示。選擇你的移動裝置作為選項,然後檢視將顯示預設介面的移動裝置 −

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP