简体   繁体   English

Android:以编程方式添加布局忽略主题

[英]Android: programmatically added layout ignores theme

I have abstract UltraSuperActivity inherited by abstract SuperActivity inherited by MyActivity . 我有由SuperActivity继承的抽象UltraSuperActivity继承的抽象MyActivity In OnCreate of SuperActivity I call setContentView(R.layout.activity_super); SuperActivity OnCreate ,我调用setContentView(R.layout.activity_super); which contains HorizontalScrollLayout into which I add the layout of current activity 其中包含HorizontalScrollLayout ,我在其中添加当前活动的布局

I add layout like this in OnCreate in MyActivity : 我在MyActivity中的OnCreate中添加这样的布局:

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: UltraSuperActivityUltraSuperActivity设置为静态:

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. 我正在使用MyButton样式,它作为主题被赋予每个按钮。 That works in activity_super layout but it does not work in activity_layout and it is displayed as common Android button. 这适用于activity_super布局,但它在activity_layout不起作用,并且显示为常用的Android按钮。 Theme is set in AndroidManifest.xml . 主题在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. 如果我将activity_layout中的MyButton样式添加到按钮它可以工作,但我不明白它为什么不使用设置主题。

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"). 尝试用getContext()(或“this”)替换getApplicationContext()。 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. 你没有使用正确的inflate方法。 You should use inflate(int, ViewGroup, boolean) where the ViewGroup is not null. 您应该使用ViewGroup不为null的inflate inflate(int, ViewGroup, boolean) Read this article for more information on the matter: 阅读本文以获取有关此事的更多信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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