在Android中为活动应用主题?

96

我知道如何将主题应用于整个应用程序,但是我该去哪里仅将主题应用于单个活动?

3个回答

173
您可以通过在清单文件中<activity>标签内部包含android:theme来为任何活动应用主题。
例如:
  1. <activity android:theme="@android:style/Theme.Dialog">
  2. <activity android:theme="@style/CustomTheme">
如果您想以编程方式设置主题,则在onCreate()方法中调用setContentView()super.onCreate()方法之前使用setTheme()方法。

1
禁用主题怎么样?在单个活动上。 - Yousha Aleayoub
@Yousha Aleayoub:你尝试过更换另一个主题吗? - Yannick
不,但我只想禁用/删除主题并使其变得基本... :) - Yousha Aleayoub
1
在活动的XML文件中,在根元素中使用tools:context=".YourAtivityName" - Faisal Naseer

37

要在Activity.java中以编程方式设置它:

public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setTheme(R.style.MyTheme); // (for Custom theme)
  setTheme(android.R.style.Theme_Holo); // (for Android Built In Theme)

  this.setContentView(R.layout.myactivity);

在Manifest.xml中的应用程序范围内设置(所有活动):

 <application
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

在 Manifest.xml 中设置 Activity 范围(单个 Activity):

  <activity
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

要创建自定义主题,您需要在themes.xml文件中声明主题,并在styles.xml文件中设置样式。


1
禁用主题怎么样?在单个活动上。 - Yousha Aleayoub
2
你为什么添加了两个 android:theme 属性? - Flame of udun
@Vineet Kaushik,“android:theme =”@ android:style/Theme.Holo“是添加Android内置主题的语法。 “android:theme =”@ style/MyTheme“是添加在您的styles.xml文件中描述的自定义主题的语法。 在实际的AndroidManifest.xml文件中,每个部分只使用其中一个,而不是两个都使用。 - Soren Stoutner
1
@Yousha Aleayoub,要禁用主题,请在styles.xml中创建一个空主题,然后使用语法android:theme=@style/MyBlankTheme - Soren Stoutner
似乎在清单文件中放置多个自定义主题无法正常工作。如果您在应用程序级别添加一个主题,然后在活动级别添加第二个主题,则仅使用应用程序级别的主题。我尝试为每个活动添加具有不同“外观”的主题,但效果不佳。 - Peter

8
在调用setContentView()之前,调用setTheme(android.R.style...),将“...”替换为您需要的主题(例如:Theme、Theme_NoTitleBar等)。如果您使用的是自定义主题,则替换整个内容,这样您就会得到setTheme(yourThemesResouceId)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接