如何仅在 Android 中将主题应用到活动?


此示例演示了如何在安卓中将主题应用到某一项活动。

步骤 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: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 − 添加以下代码到 src/MainActivity.java

import android.support.v7.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 − 添加以下代码到 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" android:theme="@style/Theme.AppCompat.Dialog.MinWidth">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

让我们尝试运行您的应用程序。我假设您已将实际的 Android 移动设备连接到电脑。要从安卓工作室运行该应用,请打开一个项目的活动文件并单击工具栏上的运行  图标。选择移动设备作为选项,然后查看移动设备,它会显示您的默认屏幕 −

单击 此处 下载项目代码。

更新时间: 2019 年 7 月 31 日

664 浏览量

开辟你的职业

完成课程来获得认证

开始学习
广告
© . All rights reserved.