2013-02-22 73 views
19

我以编程方式创建了一个textView。有没有一种方法可以设置这个textView的风格?类似的东西如何以编程方式设置textView的样式?

style="@android:style/TextAppearance.DeviceDefault.Small" 

如果我有一个layout.xml文件,我会使用它。

+0

您不能务实地设置任何视图的样式。但你可以设置视图的个别属性 – 2013-02-22 08:53:37

+0

可能重复[Android - 以编程方式设置TextView TextStyle?](http://stackoverflow.com/questions/7919173/android-set-textview-textstyle-programmatically) – 2016-12-02 09:31:10

回答

34

您无法以编程方式设置视图的样式,但您可能可以执行类似textView.setTextAppearance(context, android.R.style.TextAppearance_Small);的操作。

+0

此方法被标记为已弃用。 – pkuszewski 2016-02-05 13:50:46

+7

使用'if(Build.VERSION.SDK_INT <23){textView.setTextAppearance(context,android.R.style。TextAppearance_Small); } else { textView.setTextAppearance(android.R.style.TextAppearance_Small); }' – Nedko 2016-02-09 15:38:18

27

目前不可能以编程方式设置View的样式。

要解决这个问题,你可以创建一个指定样式的模板布局xml文件,例如在res/layout创建tvtemplate.xml与以下内容:

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="This is a template" 
     style="@android:style/TextAppearance.DeviceDefault.Small" /> 

然后充气这个实例化新的TextView:

TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null); 
+1

我喜欢这个解决方案比接受的答案更好,因为它支持OP要求的样式(我想要)。此外,它总是感觉如此....错误....使用android.widget构造函数。 – 2015-08-26 12:45:31

4

试试这个

textview.setTextAppearance(context, R.style.yourstyle); 

这可能无法正常尝试使用像这样的textview创建一个xml

textviewstyle.xml 

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     style="@android:style/TextAppearance.DeviceDefault.Small" /> 

为了获得所需的样式膨胀包含的TextView

TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvstyle, null); 
3

其实XML,这是可能的API级别的21

的TextView有一个4 parameter constructor

TextView (Context context, 
      AttributeSet attrs, 
      int defStyleAttr, 
      int defStyleRes) 

中间两个在这种情况下参数不是必需的。下面的代码直接在活动中创建一个TextView,只定义了它的样式资源:

TextView myStyledTextView = new TextView(this, null, 0, R.style.my_style); 
0
@Deprecated 
public void setTextAppearance(Context context, @StyleRes int resId) 

这种方法已被弃用由于Android SKD 23

,你可以使用安全的版本:

if (Build.VERSION.SDK_INT < 23) { 
    super.setTextAppearance(context, resId); 
} else { 
    super.setTextAppearance(resId); 
} 
相关问题