Android:以编程方式设置视图样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11723881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: set view style programmatically
提问by Jim
Here's XML:
这是 XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/LightStyle"
android:layout_width="fill_parent"
android:layout_height="55dip"
android:clickable="true"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
</RelativeLayout>
How to set style
attribute programmatically?
如何以style
编程方式设置属性?
采纳答案by Blundell
Technically you can apply styles programmatically, with custom views anyway:
从技术上讲,您可以通过自定义视图以编程方式应用样式:
private MyRelativeLayout extends RelativeLayout {
public MyRelativeLayout(Context context) {
super(context, null, R.style.LightStyle);
}
}
The one argument constructor is the one used when you instantiate views programmatically.
one 参数构造函数是您以编程方式实例化视图时使用的构造函数。
So chain this constructor to the super that takes a style parameter.
因此,将此构造函数链接到采用样式参数的 super。
RelativeLayout someLayout = new MyRelativeLayout(new ContextThemeWrapper(this,R.style.RadioButton));
Or as @Dori pointed out simply:
或者正如@Dori 简单指出的那样:
RelativeLayout someLayout = new RelativeLayout(new ContextThemeWrapper(activity,R.style.LightStyle));
回答by Benjamin Piette
What worked for me:
什么对我有用:
Button b = new Button(new ContextThemeWrapper(this, R.style.ButtonText), null, 0);
- Use a ContextThemeWrapper
- 使用 ContextThemeWrapper
AND
和
- Use the 3-arguments constructor (won't work without this)
- 使用 3-arguments 构造函数(没有这个就不能工作)
回答by Korhan Ozturk
Update: At the time of answering this question (mid 2012, API level 14-15), setting the view programmatically was not an option (even though there were some non-trivial workarounds) whereas this has been made possible after the more recent API releases. See @Blundell's answer for details.
更新:在回答这个问题时(2012 年年中,API 级别 14-15),以编程方式设置视图不是一个选项(即使有一些重要的解决方法),而在更新的 API 之后这已经成为可能发布。有关详细信息,请参阅@Blundell 的回答。
OLD Answer:
旧答案:
You cannotset a view's style programmatically yet, but you may find this threaduseful.
您还不能以编程方式设置视图的样式,但您可能会发现此线程很有用。
回答by Alon Kogan
For a new Button/TextView:
对于新的 Button/TextView:
Button mMyButton = new Button(new ContextThemeWrapper(this, R.style.button_disabled), null, 0);
For an existing instance:
对于现有实例:
mMyButton.setTextAppearance(this, R.style.button_enabled);
For Image or layouts:
对于图像或布局:
Image mMyImage = new ImageView(new ContextThemeWrapper(context, R.style.article_image), null, 0);
回答by Nathanael
If you'd like to continue using XML (which the accepted answer doesn't let you do) and set the style after the view has been created you may be able to use the Paris library which supports a subset of all available attributes.
如果您想继续使用 XML(接受的答案不允许您这样做)并在创建视图后设置样式,您可以使用支持所有可用属性子集的 Paris 库。
Since you're inflating your view from XML you'd need to specify an id in the layout:
由于您是从 XML 扩充视图,因此您需要在布局中指定一个 id:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/my_styleable_relative_layout"
style="@style/LightStyle"
...
Then when you need to change the style programmatically, after the layout has been inflated:
然后当您需要以编程方式更改样式时,在布局膨胀后:
// Any way to get the view instance will do
RelativeLayout myView = findViewById(R.id.my_styleable_relative_layout);
// This will apply all the supported attribute values of the style
Paris.style(myView).apply(R.style.LightStyle);
For more: the list of supported view types and attributes(includes background, padding, margin, etc. and can easily be extended) and installation instructions with additional documentation.
更多信息:支持的视图类型和属性列表(包括背景、填充、边距等,可以轻松扩展)和安装说明以及附加文档。
Disclaimer: I'm the original author of said library.
免责声明:我是上述图书馆的原作者。
回答by FOMDeveloper
You can apply a style to your activity by doing:
您可以通过执行以下操作将样式应用于您的活动:
super.setTheme( R.style.MyAppTheme );
or Android default:
或安卓默认:
super.setTheme( android.R.style.Theme );
in your activity, before setContentView()
.
在您的活动中,之前setContentView()
。
回答by Defuera
Non of the provided answers are correct.
提供的答案均不正确。
You CAN set style programatically.
您可以以编程方式设置样式。
Short answer is take a look at http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/content/Context.java#435
Long answer. Here's my snippet to set custom defined style programatically to your view:
长答案。这是我以编程方式为您的视图设置自定义样式的代码段:
1) Create a style in your styles.xml file
1)在你的styles.xml文件中创建一个样式
<style name="MyStyle">
<item name="customTextColor">#39445B</item>
<item name="customDividerColor">#8D5AA8</item>
</style>
Do not forget to define your custom attributes in attrs.xml file
不要忘记在 attrs.xml 文件中定义您的自定义属性
My attrsl.xml file:
我的 attrsl.xml 文件:
<declare-styleable name="CustomWidget">
<attr name="customTextColor" format="color" />
<attr name="customDividerColor" format="color" />
</declare-styleable>
Notice you can use any name for your styleable (my CustomWidget)
请注意,您可以为样式(我的 CustomWidget)使用任何名称
Now lets set the style to the widget Programatically Here's My simple widget:
现在让我们以编程方式将样式设置为小部件这是我的简单小部件:
public class StyleableWidget extends LinearLayout {
private final StyleLoader styleLoader = new StyleLoader();
private TextView textView;
private View divider;
public StyleableWidget(Context context) {
super(context);
init();
}
private void init() {
inflate(getContext(), R.layout.widget_styleable, this);
textView = (TextView) findViewById(R.id.text_view);
divider = findViewById(R.id.divider);
setOrientation(VERTICAL);
}
protected void apply(StyleLoader.StyleAttrs styleAttrs) {
textView.setTextColor(styleAttrs.textColor);
divider.setBackgroundColor(styleAttrs.dividerColor);
}
public void setStyle(@StyleRes int style) {
apply(styleLoader.load(getContext(), style));
}
}
layout:
布局:
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:layout_gravity="center"
android:text="@string/styleble_title" />
<View
android:id="@+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</merge>
And finally StyleLoader class implementation
最后 StyleLoader 类实现
public class StyleLoader {
public StyleLoader() {
}
public static class StyleAttrs {
public int textColor;
public int dividerColor;
}
public StyleAttrs load(Context context, @StyleRes int styleResId) {
final TypedArray styledAttributes = context.obtainStyledAttributes(styleResId, R.styleable.CustomWidget);
return load(styledAttributes);
}
@NonNull
private StyleAttrs load(TypedArray styledAttributes) {
StyleAttrs styleAttrs = new StyleAttrs();
try {
styleAttrs.textColor = styledAttributes.getColor(R.styleable.CustomWidget_customTextColor, 0);
styleAttrs.dividerColor = styledAttributes.getColor(R.styleable.CustomWidget_customDividerColor, 0);
} finally {
styledAttributes.recycle();
}
return styleAttrs;
}
}
You can find fully working example at https://github.com/Defuera/SetStylableProgramatically
您可以在https://github.com/Defuera/SetStylableProgramatically找到完整的示例
回答by convexHull
This is quite old question but solution that worked for me now is to use 4th parameter of constructor defStyleRes
- if available.. on view... to set style
这是一个很老的问题,但现在对我有用的解决方案是使用构造函数的第四个参数defStyleRes
- 如果可用......在视图中......设置样式
Following works for my purposes (kotlin):
以下适用于我的目的(kotlin):
val textView = TextView(context, null, 0, R.style.Headline1)
回答by Sai Gopi N
the simple way is passing through constructor
简单的方法是通过构造函数
RadioButton radioButton = new RadioButton(this,null,R.style.radiobutton_material_quiz);
回答by guogangj
This is my simple example, the key is the ContextThemeWrapper
wrapper, without it, my style does not work, and using the three parameters constructor of the View.
这是我的简单例子,关键是ContextThemeWrapper
wrapper,没有它,我的风格不行,使用View的三个参数构造函数。
ContextThemeWrapper themeContext = new ContextThemeWrapper(this, R.style.DefaultLabelStyle);
TextView tv = new TextView(themeContext, null, 0);
tv.setText("blah blah ...");
layout.addView(tv);