【发布时间】:2010-07-13 13:42:34
【问题描述】:
有没有人知道如何在运行时为TextView 设置样式:
类似的东西
myTextView.setStyle(R.style.mystyle);
【问题讨论】:
标签: android
有没有人知道如何在运行时为TextView 设置样式:
类似的东西
myTextView.setStyle(R.style.mystyle);
【问题讨论】:
标签: android
非常简单,只需使用 setTextApparence 和你的风格
myTextView.setTextAppearance(getApplicationContext(), R.style.boldText);
【讨论】:
setTextAppearance(Context context, @StyleRes int resId) 已被弃用,我们应该改用 setTextAppearance(@StyleRes int resId)
您必须手动设置您更改的样式的每个元素,AFAIK 无法在运行时设置样式。
myTextView.setTextAppearance
myTextView.setTextSize
myTextView.setTextColor
【讨论】:
我还没有找到(遗憾的是)在运行时更改样式的方法。
如果只是改变复选框的外观(正如您在另一个答案的评论中提到的那样),您可以使用这个:
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文件。
【讨论】:
我正在尝试自己做类似的事情。
我的原因是我想使用我自己的主题中的样式,但是我的用户界面布局完全是在代码中生成的(使用自定义布局构建器),没有在 XML 中定义任何小部件。所以我无法在我的小部件的 XML 布局中设置样式 - 没有任何 XML 布局。
我想我可以通过使用在我的小部件的代码中设置这种样式
TypedArray a =
context.obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
这里(在我看来)似乎
属性集设置=空;因为这是 XML inflater 所提供的。
int[] attrs = R.styleable.MyWidget;定义我要查看的属性。
int defStyleAttr = myWidgetStyle;这是在我的主题中定义的对 MyWidget 样式的引用。这些都是在 res/values 中的 XML 文件中定义的。 “myWidgetStyle”遵循 android 开发人员在其代码中使用的名称模式。
defStyleRes = 0;我希望我不需要考虑这个。
然后获取任意属性,比如背景颜色,
颜色颜色 = a.getColor(R.styleable.MyWidget_background, R.color.my_default);
a.recycle();
这似乎确实有效——无论如何。
android 构建系统似乎很方便地生成了正确的索引以在 a.getColor 中使用,并将其命名为 R.styleable.MyWidget_background 。这个名字不是我自己起的,所以 Android 一定是使用我的 XML 来为我的可样式化 MyWidget 命名的。
我希望人们可以通过在 TypedArray 中搜索所需的属性来查找正确的索引,但这将是低效的,并且 TypedArray 看起来像是一种令人不快的装置来处理。我会用一根很长的棍子戳它!
不要
【讨论】:
TextView(上下文上下文,AttributeSet attrs,int defStyle)
虽然有可用的构造,但它似乎有问题,我尝试了这个,发现指定的样式不适用于我的视图。
经过进一步搜索得到这个归档的错误:http://code.google.com/p/android/issues/detail?id=12683
为了解决这个问题,我正在使用 setBackgroundResource、setTextAppearance 等方法:)
【讨论】: