如何在 Android 中建立透明狀態列和 ActionBar?


本例演示瞭如何在 Android 中建立透明狀態列和 ActionBar。

步驟 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"
   android:background="#222222">
   <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.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}

步驟 4 −將以下程式碼新增到 res/values/styles.xml

<resources>
   <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
      <item name="colorPrimary">@color/colorPrimary</item>
      <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
      <item name="colorAccent">@color/colorAccent<item>
   </style>
   <style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
      <item name="android:windowContentOverlay">@null</item>
      <item name="windowActionBarOverlay">true</item>
      <item name="colorPrimary">@android:color/transparent</item>
   </style>
</resources>

步驟 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">
   <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:theme="@style/AppTheme.ActionBar.Transparent">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

我們嘗試執行此應用程式。我假設你的實際 Android 移動裝置已連線到你的電腦。要從 android studio 執行該應用程式,請開啟專案的一個活動檔案並單擊工具欄中的執行  圖示。選擇你的移動裝置作為選項,然後檢視顯示預設螢幕的移動裝置 −

單擊 此處 下載專案程式碼。

更新於: 2019 年 11 月 15 日

2 千次瀏覽

開啟你的 事業

完成課程以獲得認證

開始
廣告