首页 > 解决方案 > 如何以编程方式设置按钮样式资源?

问题描述

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

自定义视图:

<?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作为根视图应用。这是初始化我的 CustomView 部分的函数

 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
    }

标签: androidandroid-layoutandroid-xml

解决方案


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

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)
    }

推荐阅读