简体   繁体   中英

Xamarin: How do I apply the following android theme to my activity at runtime?

I have the following activity which specifies the theme as an attribute

[Activity(Label = "PermissionsActivity", Theme = "@android:style/Theme.Translucent.NoTitleBar")]
public class PermissionsActivity: Activity

This works well, but how can I apply the same at runtime? Maybe by calling SetTheme in OnCreate . I can see SetTheme accepts a resource id integer. I'm having a hard time finding the corresponding Xamarin.Android constant for the aforementioned theme. Please help

Add your theme in style.xml file under Resource folder than access it from resource as int

<style name="MyTheme" parent="Theme.Translucent.NoTitleBar">
</style>

Setting in activity

this.SetTheme(Resource.Style.MyTheme);

Add this code in your onCreate Method:

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

When you add some theme in any folder under the resources of an android project what Visual studio does is it creates a corresponding int value inside the ResourceDesigner.cs file under the resources folder.

Now in Runtime when you need to add these to your code they are available as follows:

  • If the resource is a style then it is available in Resource.Style.YourResourceName
  • If the resource is a dimension then it is available in Resource.Dimen.YourResourceName
  • If the resource is a string then it is available in Resource.String.YourResourceName
  • If the resource is an image under the drawable folder then it is available in Resource.Drawable.YourResourceName
  • If the resource is an image under the mipmap folder then it is available in Resource.Mipmap.YourResourceName , And so on and so forth.

Note: These properties are always an integer.

In your case since it is a theme(which is basically a style)

Hence you can get it like this in an Activity:

this.SetTheme(Resource.Style.MyTheme);

And in a Fragment something like this :

this.Activity.SetTheme(Resource.Style.MyTheme);

Hope this helps,

Revert in case of queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM