相关疑难解决方法(0)

如何以编程方式在视图中设置样式属性

我从XML获得了一个视图,其代码如下:

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
Run Code Online (Sandbox Code Playgroud)

我想为按钮设置一个"样式"我怎么能在java中这样做,因为我想使用几个样式我将使用的每个按钮.

android styles

99
推荐指数
8
解决办法
20万
查看次数

为什么从Android中的代码设置样式这么复杂

如果你想设置你从代码创建的Button的样式,你必须做这样的事情;

Button  btn  = new Button (mActivity, null, R.attr.someattribute);
Run Code Online (Sandbox Code Playgroud)

在attrs.xml中,您设置了一个引用

<attr name="someStyleRef" format="reference"/>
Run Code Online (Sandbox Code Playgroud)

在styles.xml中,您可以定义主题

<resources>
  <style name="Theme.SomeTheme" parent="android:style/Theme.Black">
     <item name="someStyleRef">@style/someStyle</item>
  </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

在styles.xml中的lates定义为例如

<style name="someStyle">
        <item name="android:layout_width">2px</item>
        <item name="android:layout_height">fill_parent</item>
        <item name="android:background">@drawable/actionbar_compat_separator</item>
 </style>
Run Code Online (Sandbox Code Playgroud)

这是有效的,根据我的理解,这是从Android中的代码在视图上设置样式的方法.这似乎过于复杂.按钮的第三个构造函数Argument可以很容易地接受样式ID R.style.XXX

谁能解释为什么需要这种额外的复杂性?

android themes

35
推荐指数
1
解决办法
2万
查看次数

setTextAppearance通过代码引用自定义属性

我正在使用自定义属性在我的应用程序中实现主题切换.我定义了以下属性:

<resources>
    <attr name="TextAppearance_Footer" format="reference"></attr>
</resources>
Run Code Online (Sandbox Code Playgroud)

我有两个主题,以不同的方式定义此属性:

<style name="NI_AppTheme.Dark">
    <item name="TextAppearance_Footer">@style/Footer</item>
</style>
Run Code Online (Sandbox Code Playgroud)

@style/Footer定义如下:

<style name="Footer" parent="@android:style/TextAppearance.Large">
    <item name="android:textColor">#00FF00</item> // Green
</style>
Run Code Online (Sandbox Code Playgroud)

现在,如果我尝试将此样式设置为TextView使用:

textView.setTextAppearance(this, R.attr.TextAppearance_Footer);
Run Code Online (Sandbox Code Playgroud)

它不起作用(即不将文本设置为绿色).但是,如果我使用xml通过xml指定文本外观:

android:textAppearance="?TextAppearance_Footer"
Run Code Online (Sandbox Code Playgroud)

它工作正常.我能错过什么?我需要设置属性,因为我想动态地在主题之间切换.

附加信息:

如果我使用:

textView.setTextAppearance(this, R.style.NI_AppTheme.Dark);
Run Code Online (Sandbox Code Playgroud)

它似乎工作正常.

编辑:经过测试的工作解决方案(感谢@nininho):

Resources.Theme theme = getTheme();
TypedValue styleID = new TypedValue();
if (theme.resolveAttribute(R.attr.Channel_Title_Style, styleID, true)) {
     channelTitle.setTextAppearance(this, styleID.data);
}
Run Code Online (Sandbox Code Playgroud)

android

5
推荐指数
1
解决办法
5481
查看次数

标签 统计

android ×3

styles ×1

themes ×1