Ben*_*Ben 243 android coding-style textview
我正在尝试使用像这样的样式的TextView构造函数:
TextView myText = new TextView(MyActivity.this, null, R.style.my_style );
但是,当我这样做时,文本视图似乎不采用样式(我通过在静态对象上设置它来验证样式).
我也尝试过使用myText.setTextAppearance(MyActivity.this, R.style.my_style)
但它也不起作用
Dan*_*ick 310
我不相信你可以以编程方式设置样式.要解决此问题,您可以创建一个模板布局xml文件,并指定样式,例如在res/layout create 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="@style/my_style" />
Run Code Online (Sandbox Code Playgroud)
然后膨胀这个实例化你的新TextView:
TextView myText = (TextView)getLayoutInflater().inflate(R.layout.tvtemplate, null);
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.
小智 117
您可以创建一个通用样式,并在多个文本视图上重复使用它,如下所示:
textView.setTextAppearance(this, R.style.MyTextStyle);
Run Code Online (Sandbox Code Playgroud)
编辑:这是指Context
max*_*nna 94
您可以将ContextThemeWrapper传递给构造函数,如下所示:
TextView myText = new TextView(new ContextThemeWrapper(MyActivity.this, R.style.my_style));
Run Code Online (Sandbox Code Playgroud)
Dan*_*son 16
您可以在构造函数中设置样式(但不能动态更改/设置样式).
View(Context, AttributeSet, int)
(这int
是一种风格资源)
参数int defStyleAttr
不指定样式.从Android文档:
defStyleAttr - 当前主题中的一个属性,包含对为视图提供默认值的样式资源的引用.可以为0以查找默认值.
要在View构造函数中设置样式,我们有两种可能的解决方案:
使用ContextThemeWrapper:
ContextThemeWrapper wrappedContext = new ContextThemeWrapper(yourContext, R.style.your_style);
TextView textView = new TextView(wrappedContext, null, 0);
Run Code Online (Sandbox Code Playgroud)使用四参数构造函数(从LOLLIPOP开始可用):
TextView textView = new TextView(yourContext, null, 0, R.style.your_style);
Run Code Online (Sandbox Code Playgroud)两个解决方案的关键 - defStyleAttr
参数应为0以将我们的样式应用于视图.
归档时间: |
|
查看次数: |
185900 次 |
最近记录: |