【问题标题】:How to set Button style resource programmatically?如何以编程方式设置按钮样式资源?
【发布时间】:2019-08-12 09:16:36
【问题描述】:

我想以编程方式设置按钮样式。原因是我有包含Button 的CustomView。我使用<declare-styleable> 中的自定义参数将样式ID 发送到我的CustomView。现在我需要为我的 CustomView 中的 Button 而不是整个视图设置按钮样式。

自定义视图:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:indeterminate="true"
        android:layout_gravity="center"
        android:indeterminateTint="@color/colorText"/>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</FrameLayout>

我的代码中的自定义视图:

<myproject.CustomView
                    android:id="@+id/btn"
                    app:progressColor="@color/colorText"
                    app:l_buttonText="@string/text"
                    app:l_buttonStyle="@style/dialog_outlined"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="48dp" />

我想要实现的是仅为 Button 设置样式(从 app:l_buttonStyle 获得的值)但我必须以编程方式执行此操作,因为如果我在 XML 中设置样式,它将作为根视图应用于 FrameLayout .这是初始化部分自定义视图的函数

 private fun init(context: Context) {
        //Init default values
        View.inflate(context, R.layout.loading_button, this)
        button = findViewById(R.id.button)
        progressBar = findViewById(R.id.progressBar)
        progressBar?.setGone()

        //Now I need to set style for my inflated Button from XML layout
    }

【问题讨论】:

  • 如果您的布局仅包含 2 个视图,则在代码中创建所有视图会更容易,并且在创建时使用您通过 styleable 收到的样式。
  • 是的,但是我在我的代码中的多个地方都使用了这个布局。这意味着我必须在使用此按钮的代码的每个部分中实现进度显示/隐藏和按钮文本显示/隐藏。这样我只想调用一个功能按钮?.setloading(boolean)。
  • 我不确定我是否理解正确。您已经创建了在初始化部分将设置样式的自定义视图。等效地,您不能在 init 中使用 `View.inflate(context, R.layout.loading_button, this)`,而是在其中创建 Button 和 Progress 作为普通视图并使用 addView 方法添加它,在这种情况下您将能够创建按钮以你的风格
  • 嗯,好的。是的,我的 CustomView 类扩展了 FrameLayout

标签: android android-layout android-xml


【解决方案1】:

自定义视图中的视图必须以编程方式创建,并且在初始化视图时必须应用自定义样式。视图初始化后,无法设置样式。

val button = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Button(this, null, 0, R.style.BtnStyle)
    } else {
        var themeWrapper = ContextThemeWrapper(this, R.style.BtnStyle)
        Button(themeWrapper, null, 0)
    }

【讨论】:

    猜你喜欢
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多