Android:运行时设置TextView样式

12

有没有人知道如何在运行时为TextView设置样式:

就像这样

myTextView.setStyle(R.style.mystyle);
5个回答

25

非常简单,只需使用setTextAppearance和您的样式即可

 myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);

有没有类似的东西适用于LinearLayout? - Matthias B
只是一个快速的提示,setTextAppearance(Context context, @StyleRes int resId)已经被弃用了,我们应该使用setTextAppearance(@StyleRes int resId)代替。 - AllDayAmazing

3

如果您想更改样式,您需要手动设置每个元素的样式,目前没有办法在运行时设置样式。

myTextView.setTextAppearance
myTextView.setTextSize
myTextView.setTextColor

谢谢您的回答,但如果我想要动态添加多个星形复选框,似乎没有办法在运行时设置样式。但在我的情况下,我想要添加这个星形复选框。<CheckBox style="?android:attr/starStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" /> 我该怎么做? - Mohammad Rukab

2

很遗憾,我仍然没有找到在运行时更改样式的方法。

如果只是想更改复选框的外观(如您在另一个答案的评论中提到),可以使用以下代码:

myCheckbox.setButtonDrawable(R.drawable.star_checkbox);

在drawable目录下有一个star_checkbox.xml文件,根据其状态描述复选框的背景,例如:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_focused="true"
        android:drawable="@drawable/star_checkbox_checked_focused" />

    <item android:state_checked="false" android:state_focused="true"
        android:drawable="@drawable/checkbox_not_checked_focused" />

    <item android:state_checked="false" 
        android:drawable="@drawable/checkbox_not_checked" />

    <item android:state_checked="true" 
        android:drawable="@drawable/checkbox_checked" />
</selector>

你需要在drawable目录中拥有对应的PNG文件。

0

我正在尝试自己做类似的事情。

我的原因是我想使用自己主题中的样式,但是我的用户界面布局完全是在代码中生成的(使用自定义布局构建器),而没有在XML中定义任何小部件。因此,我无法在小部件的XML布局中设置样式-因为没有任何XML布局。

我认为我将能够通过使用

TypedArray a =

context.obtainStyledAttributes(AttributeSet set,int[] attrs,int defStyleAttr,int defStyleRes)

在我的小部件代码中设置此样式。

在这里,对我来说似乎是这样

  • AttributeSet set = null;这是XML布局解析器提供的内容。

  • int[] attrs = R.styleable.MyWidget; 定义我想要查看的属性。

  • int defStyleAttr = myWidgetStyle; 这是一个引用,在我的主题中定义,用于MyWidget的样式。这两个都在res/values中的XML文件中定义。 “myWidgetStyle”遵循Android开发人员在他们的代码中使用的命名模式。

  • defStyleRes = 0; 我希望不需要考虑这个。

  • 然后,要获取任何属性,例如背景颜色,

    Color color = a.getColor(R.styleable.MyWidget_background, R.color.my_default);

    a.recycle();

    这似乎有效 - 目前为止。

    看起来,Android构建系统方便地生成了在a.getColor中使用的正确索引,并将其命名为R.styleable.MyWidget_background。我没有自己命名,所以Android必须使用我的样式MyWidget的XML来完成它。

    我希望可以通过搜索所需属性的TypedArray来查找正确的索引,但那样效率低下,而且TypedArray看起来像是一个不愉快的装置。我会用一根非常长的棍子去戳它!


    0

    TextView (Context context, AttributeSet attrs, int defStyle)

    虽然有可用的构造函数,但似乎存在错误。我尝试了一下,发现指定的样式不会应用于我的视图。

    进一步搜索后,发现了这个已经被报告的 bug:http://code.google.com/p/android/issues/detail?id=12683

    为了解决这个问题,我大量使用了 setBackgroundResource、setTextAppearance 等方法 :)


    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接