Android 如何以编程方式在视图中设置样式属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2016249/
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
How to programmatically set style attribute in a view
提问by Lint_
I'm getting a view from the XML with the code below:
我使用以下代码从 XML 中获取视图:
Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
I would like to set a "style" for the button how can I do that in java since a want to use several style for each button I will use.
我想为按钮设置一个“样式”,我该如何在 java 中做到这一点,因为我想为我将使用的每个按钮使用多种样式。
采纳答案by Christopher Orr
Generally you can't change styles programmatically; you can set the look of a screen, or part of a layout, or individual button in your XML layout using themes or styles. Themes can, however, be applied programmatically.
通常,您不能以编程方式更改样式;您可以使用主题或样式在 XML 布局中设置屏幕、布局的一部分或单个按钮的外观。但是,可以通过编程方式应用主题。
There is also such a thing as a StateListDrawable
which lets you define different drawables for each state the your Button
can be in, whether focused, selected, pressed, disabled and so on.
还有一个这样的东西,StateListDrawable
它可以让你为你Button
可以处于的每个状态定义不同的可绘制对象,无论是聚焦、选中、按下、禁用等等。
For example, to get your button to change colour when it's pressed, you could define an XML file called res/drawable/my_button.xml
directory like this:
例如,要让您的按钮在按下时改变颜色,您可以定义一个名为res/drawable/my_button.xml
directory的 XML 文件,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@drawable/btn_pressed" />
<item
android:state_pressed="false"
android:drawable="@drawable/btn_normal" />
</selector>
You can then apply this selector to a Button
by setting the property android:background="@drawable/my_button"
.
然后,您可以Button
通过设置属性将此选择器应用于 a android:background="@drawable/my_button"
。
回答by beetstra
First of all, you don't need to use a layout inflater to create a simple Button. You can just use:
首先,您不需要使用布局充气器来创建一个简单的 Button。你可以只使用:
button = new Button(context);
If you want to style the button you have 2 choices: the simplest one is to just specify all the elements in code, like many of the other answers suggest:
如果您想设置按钮样式,您有两种选择:最简单的一种是在代码中指定所有元素,就像许多其他答案所建议的那样:
button.setTextColor(Color.RED);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
The other option is to define the style in XML, and apply it to the button. In the general case, you can use a ContextThemeWrapper
for this:
另一种选择是在 XML 中定义样式,并将其应用于按钮。在一般情况下,您可以ContextThemeWrapper
为此使用 a :
ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
button = new Button(newContext);
To change the text-related attributes on a TextView (or its subclasses like Button) there is a special method:
要更改 TextView(或其子类,如 Button)上的文本相关属性,有一个特殊的方法:
button.setTextAppearance(context, R.style.MyTextStyle);
This last one cannot be used to change all attributes; for example to change padding you need to use a ContextThemeWrapper
. But for text color, size, etc. you can use setTextAppearance
.
最后一个不能用于更改所有属性;例如,要更改填充,您需要使用ContextThemeWrapper
. 但是对于文本颜色、大小等,您可以使用setTextAppearance
.
回答by Dayerman
Yes, you can use for example in a button
是的,您可以在例如按钮中使用
Button b = new Button(this);
b.setBackgroundResource(R.drawable.selector_test);
回答by Kristy Welsh
You can do style attributes like so:
您可以像这样执行样式属性:
Button myButton = new Button(this, null,android.R.attr.buttonBarButtonStyle);
in place of:
代替:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
style="?android:attr/buttonBarButtonStyle"
/>
回答by cesards
If you are using the Support library, you could simply use
如果您使用的是 Support 库,则可以简单地使用
TextViewCompat.setTextAppearance(textView, R.style.AppTheme_TextStyle_ButtonDefault_Whatever);
for TextViews and Buttons. There are similar classes for the rest of Views :-)
用于文本视图和按钮。其余的视图也有类似的类:-)
回答by Micro
For anyone looking for a Material answer see this SO post: Coloring Buttons in Android with Material Design and AppCompat
对于寻找 Material 答案的任何人,请参阅此 SO 帖子:使用 Material Design 和 AppCompat 在 Android 中着色按钮
I used a combination of this answer to set the default text color of the button to white for my button: https://stackoverflow.com/a/32238489/3075340
我使用此答案的组合将按钮的默认文本颜色设置为白色:https: //stackoverflow.com/a/32238489/3075340
Then this answer https://stackoverflow.com/a/34355919/3075340to programmatically set the background color. The code for that is:
然后这个答案https://stackoverflow.com/a/34355919/3075340以编程方式设置背景颜色。代码是:
ViewCompat.setBackgroundTintList(your_colored_button,
ContextCompat.getColorStateList(getContext(),R.color.your_custom_color));
your_colored_button
can be just a regular Button
or a AppCompat button if you wish - I tested the above code with both types of buttons and it works.
your_colored_button
Button
如果你愿意,可以只是一个普通按钮或 AppCompat 按钮 - 我用两种类型的按钮测试了上面的代码并且它可以工作。
EDIT: I found that pre-lollipop devices do not work with the above code. See this post on how to add support for pre-lollipop devices: https://stackoverflow.com/a/30277424/3075340
编辑:我发现 pre-lollipop 设备不适用于上述代码。请参阅有关如何添加对棒棒糖前设备支持的帖子:https: //stackoverflow.com/a/30277424/3075340
Basically do this:
基本上这样做:
Button b = (Button) findViewById(R.id.button);
ColorStateList c = ContextCompat.getColorStateList(mContext, R.color.your_custom_color;
Drawable d = b.getBackground();
if (b instanceof AppCompatButton) {
// appcompat button replaces tint of its drawable background
((AppCompatButton)b).setSupportBackgroundTintList(c);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// Lollipop button replaces tint of its drawable background
// however it is not equal to d.setTintList(c)
b.setBackgroundTintList(c);
} else {
// this should only happen if
// * manually creating a Button instead of AppCompatButton
// * LayoutInflater did not translate a Button to AppCompatButton
d = DrawableCompat.wrap(d);
DrawableCompat.setTintList(d, c);
b.setBackgroundDrawable(d);
}
回答by biniam
The answer by @Dayerman and @h_rules is right. To give an elaborated example with code, In drawable folder, create an xml file called button_disabled.xml
@Dayerman 和 @h_rules 的答案是正确的。给出一个详细的代码示例,在 drawable 文件夹中,创建一个名为 button_disabled.xml 的 xml 文件
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="10dp">
<solid android:color="@color/silver"/>
<corners
android:bottomRightRadius="20dp"
android:bottomLeftRadius="20dp"
android:topLeftRadius="20dp"
android:topRightRadius="20dp"/>
</shape>
Then in Java,
然后在Java中,
((Button) findViewById(R.id.my_button)).setEnabled(false);
((Button) findViewById(R.id.my_button)).setBackgroundResource(R.drawable.button_disabled);
This will set the button's property to disabled and sets the color to silver.
这会将按钮的属性设置为禁用并将颜色设置为银色。
[The color is defined in color.xml as:
[颜色在 color.xml 中定义为:
<resources>
<color name="silver">#C0C0C0</color>
</resources>
回答by Nathanael
Depending on what style attributes you'd like to change you may be able to use the Paris library:
根据您想要更改的样式属性,您可以使用 Paris 库:
Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
Paris.style(view).apply(R.style.YourStyle);
Many attributes like background, padding, textSize, textColor, etc. are supported.
支持许多属性,如背景、填充、文本大小、文本颜色等。
Disclaimer: I authored the library.
免责声明:我编写了该库。
回答by Jerry Frost
At runtime, you know what style you want your button to have. So beforehand, in xml in the layout folder, you can have all ready to go buttons with the styles you need. So in the layout folder, you might have a file named: button_style_1.xml. The contents of that file might look like:
在运行时,您知道您希望按钮具有什么样式。因此,事先,在布局文件夹中的 xml 中,您可以准备好所有具有所需样式的按钮。因此,在布局文件夹中,您可能有一个名为:button_style_1.xml 的文件。该文件的内容可能如下所示:
<?xml version="1.0" encoding="utf-8"?>
<Button
android:id="@+id/styleOneButton"
style="@style/FirstStyle" />
If you are working with fragments, then in onCreateView you inflate that button, like:
如果您正在使用片段,那么在 onCreateView 中,您可以膨胀该按钮,例如:
Button firstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);
where container is the ViewGroup container associated with the onCreateView method you override when creating your fragment.
其中 container 是与您在创建片段时覆盖的 onCreateView 方法关联的 ViewGroup 容器。
Need two more such buttons? You create them like this:
还需要两个这样的按钮吗?你像这样创建它们:
Button secondFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);
Button thirdFirstStyleBtn = (Button) inflater.inflate(R.layout.button_style_1, container, false);
You can customize those buttons:
您可以自定义这些按钮:
secondFirstStyleBtn.setText("My Second");
thirdFirstStyleBtn.setText("My Third");
Then you add your customized, stylized buttons to the layout container you also inflated in the onCreateView method:
然后将自定义的样式化按钮添加到也在 onCreateView 方法中膨胀的布局容器中:
_stylizedButtonsContainer = (LinearLayout) rootView.findViewById(R.id.stylizedButtonsContainer);
_stylizedButtonsContainer.addView(firstStyleBtn);
_stylizedButtonsContainer.addView(secondFirstStyleBtn);
_stylizedButtonsContainer.addView(thirdFirstStyleBtn);
And that's how you can dynamically work with stylized buttons.
这就是您可以动态处理风格化按钮的方式。
回答by Kostyantin2216
I made a helper interface for this using the holder pattern.
我使用持有人模式为此制作了一个辅助界面。
public interface StyleHolder<V extends View> {
void applyStyle(V view);
}
Now for every style you want to use pragmatically just implement the interface, for example:
现在,对于您想要务实使用的每种样式,只需实现接口,例如:
public class ButtonStyleHolder implements StyleHolder<Button> {
private final Drawable background;
private final ColorStateList textColor;
private final int textSize;
public ButtonStyleHolder(Context context) {
TypedArray ta = context.obtainStyledAttributes(R.style.button, R.styleable.ButtonStyleHolder);
Resources resources = context.getResources();
background = ta.getDrawable(ta.getIndex(R.styleable.ButtonStyleHolder_android_background));
textColor = ta.getColorStateList(ta.getIndex(R.styleable.ButtonStyleHolder_android_textColor));
textSize = ta.getDimensionPixelSize(
ta.getIndex(R.styleable.ButtonStyleHolder_android_textSize),
resources.getDimensionPixelSize(R.dimen.standard_text_size)
);
// Don't forget to recycle!
ta.recycle();
}
@Override
public void applyStyle(Button btn) {
btn.setBackground(background);
btn.setTextColor(textColor);
btn.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}
}
Declare a stylable in your attrs.xml
, the styleable for this example is:
在你的 中声明一个样式,attrs.xml
这个例子的样式是:
<declare-styleable name="ButtonStyleHolder">
<attr name="android:background" />
<attr name="android:textSize" />
<attr name="android:textColor" />
</declare-styleable>
Here is the style declared in styles.xml
:
这是在 中声明的样式styles.xml
:
<style name="button">
<item name="android:background">@drawable/button</item>
<item name="android:textColor">@color/light_text_color</item>
<item name="android:textSize">@dimen/standard_text_size</item>
</style>
And finally the implementation of the style holder:
最后是样式持有者的实现:
Button btn = new Button(context);
StyleHolder<Button> styleHolder = new ButtonStyleHolder(context);
styleHolder.applyStyle(btn);
I found this very helpful as it can be easily reused and keeps the code clean and verbose, i would recommend using this only as a local variable so we can allow the garbage collector to do its job once we're done with setting all the styles.
我发现这非常有用,因为它可以轻松重用并保持代码干净和冗长,我建议仅将其用作局部变量,以便我们可以在完成所有样式的设置后让垃圾收集器完成其工作.