Android:在运行时设置TextView样式

时间:2010-07-13 13:42:35

标签: android

是否有任何机构知道如何在运行时为TextView设置样式:

类似这样的事情

myTextView.setStyle(R.style.mystyle);

5 个答案:

答案 0 :(得分:25)

使用setTextApparence和你的风格

非常简单
 myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);

答案 1 :(得分:3)

你必须手动设置你改变的样式的每个元素,在运行时没有办法setStyle,AFAIK。

myTextView.setTextAppearance
myTextView.setTextSize
myTextView.setTextColor

答案 2 :(得分:2)

我仍然没有(遗憾地)找到一种在运行时更改Style的方法。

如果它只是改变复选框外观(正如你在另一个答案的评论中提到的那样),你可以使用它:

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>

此外,您还需要相应的png文件。

答案 3 :(得分:0)

我正在努力做类似的事情。

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

我想我可以使用

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

TypedArray a =

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

这对我来说似乎是

  1. AttributeSet set = null;因为这是XML inflater提供的内容。

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

  3. int defStyleAttr = myWidgetStyle;这是我的主题中定义的引用,用于MyWidget的样式。这些都是在res / values的XML文件中定义的。 “myWidgetStyle”遵循Android开发人员在其代码中使用的名称模式。

  4. defStyleRes = 0;我希望我不需要考虑这一点。

  5. 然后获取任何属性,例如背景颜色

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

    a.recycle();

    这似乎确实有效 - 无论如何。

    似乎android构建系统可以方便地生成在a.getColor中使用的正确索引,并将其命名为R.styleable.MyWidget_background。我自己没有这个名字,所以Android必须使用我的XML为我的风格MyWidget完成它。

    我希望通过在TypedArray中搜索所需的属性来查找正确的索引,但这样效率很低,而且TypedArray看起来像是一个令人不快的处理方法。我会用很长的棒来戳它!

答案 4 :(得分:0)

TextView(Context context,AttributeSet attrs,int defStyle)

虽然有可用的结构,但看起来它有点儿,我试过这个,发现指定的样式不适用于我的观点。

在进一步搜索后得到了这个提交的错误:http://code.google.com/p/android/issues/detail?id=12683

要解决此问题,我将大大使用setBackgroundResource,setTextAppearance等方法:)