简体   繁体   中英

Android: programmatically added layout ignores theme

I have abstract UltraSuperActivity inherited by abstract SuperActivity inherited by MyActivity . In OnCreate of SuperActivity I call setContentView(R.layout.activity_super); which contains HorizontalScrollLayout into which I add the layout of current activity

I add layout like this in OnCreate in MyActivity :

LinearLayout activity_layout = (LinearLayout)inflater.inflate(R.layout.activity_layout, null);
HorizontalScrollView application_contents = (HorizontalScrollView)findViewById(R.id.application_contents);
HorizontalScrollView.LayoutParams cp = new HorizontalScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
some more code...
application_contents.addView(activity_layout, cp);

Inflater is set up in UltraSuperActivity as static:

if(inflater == null){
    inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.setFactory(CustomViewFactory.getInstance()); // we add our factory for our views
}

I am using MyButton style which as a theme is given to every button. That works in activity_super layout but it does not work in activity_layout and it is displayed as common Android button. Theme is set in AndroidManifest.xml . If I add MyButton style in the activity_layout to the button it works but I don't understand why it does not use the set up theme.

I'm guessing you are not getting your activity theme, rather you are getting the application theme, which in this case is most likely the default. Try replacing getApplicationContext() with getContext() (or "this"). A common mistake is to think the Application Context and an Activity Context are the same thing.

You're not using the proper inflate method. You should use inflate(int, ViewGroup, boolean) where the ViewGroup is not null. Read this article for more information on the matter:

http://www.doubleencore.com/2013/05/layout-inflation-as-intended/

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