如何以编程方式设置样式属性在视图中视图、样式、属性、方式

2023-09-11 23:56:07 作者:藐视的王者

我收到请从下方的code中的XML一个观点:

I'm getting a view from the XML with the code below:

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);

我想设置一个风格的按钮,我该怎么做,在Java中,因为一个想用几个样式为每个按钮,我将使用。

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.

推荐答案

通常你不能改变风格编程;您可以使用主题设置屏幕的外观或布局的一部分,或者单独的按钮,在你的XML布局或样式的。主题可以,但是,通过编程应用的。

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.

还有这样的事情作为一个StateListDrawable它可以让你对每个国家定义不同的可绘制了你的按钮可在,无论是重点,选择,pressed,残疾人等。

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.

例如,让你的按钮来改变颜色时,它的pressed,您可以定义一个名为 RES /绘制/ my_button.xml 这样的目录中的XML文件

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:

<?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>

背景=@可绘制/ my_button。

You can then apply this selector to a Button by setting the property android:background="@drawable/my_button".