【问题标题】:Xamarin: How do I apply the following android theme to my activity at runtime?Xamarin:如何在运行时将以下 android 主题应用于我的活动?
【发布时间】:2018-10-05 10:30:32
【问题描述】:
我有以下将主题指定为属性的活动
[Activity(Label = "PermissionsActivity", Theme = "@android:style/Theme.Translucent.NoTitleBar")]
public class PermissionsActivity: Activity
这很好用,但我如何在运行时应用它呢?也许通过在OnCreate 中调用SetTheme。我可以看到 SetTheme 接受一个资源 id 整数。我很难为上述主题找到相应的 Xamarin.Android 常量。请帮忙
【问题讨论】:
标签:
c#
android
xamarin
android-activity
xamarin.android
【解决方案1】:
将您的主题添加到资源文件夹下的style.xml 文件中,而不是以int 的身份从资源中访问它
<style name="MyTheme" parent="Theme.Translucent.NoTitleBar">
</style>
活动设置
this.SetTheme(Resource.Style.MyTheme);
【解决方案2】:
在你的 onCreate 方法中添加这段代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Call setTheme before creation of any(!) View.
setTheme(android.R.style.Theme_Dark);
// ...
setContentView(R.layout.main);
For reference check this Link
【解决方案3】:
当您在 android 项目的资源下的任何文件夹中添加一些主题时,Visual Studio 所做的是它在资源文件夹下的 ResourceDesigner.cs 文件中创建相应的 int 值。
现在在运行时,当您需要将这些添加到您的代码中时,它们可用如下:
- 如果资源是样式,那么它在
Resource.Style.YourResourceName 中可用
- 如果资源是维度,那么它在
Resource.Dimen.YourResourceName 中可用
- 如果资源是字符串,那么它在
Resource.String.YourResourceName 中可用
- 如果资源是可绘制文件夹下的图像,则在
Resource.Drawable.YourResourceName 中可用
- 如果资源是 mipmap 文件夹下的图像,则它在
Resource.Mipmap.YourResourceName 中可用,依此类推。
注意:这些属性始终是整数。
在你的情况下,因为它是一个主题(基本上是一种风格)
因此您可以在 Activity 中像这样获得它:
this.SetTheme(Resource.Style.MyTheme);
在片段中是这样的:
this.Activity.SetTheme(Resource.Style.MyTheme);
希望对你有帮助,
在查询时还原。