android - 如何以编程方式设置按钮样式资源?
问题描述
我想以编程方式设置按钮样式。原因是我有 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
}
解决方案
自定义视图中的视图必须以编程方式创建,并且在初始化视图时必须应用自定义样式。视图初始化后,无法设置样式。
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)
}
推荐阅读
- kubernetes - 描述 pod 信息
- go - 模拟标准输入和扫描线上的连续输入
- c++ - 参数帮助字符串在函数向导 (C++ XLL) 中丢失最后一个字符
- pyspark - Spark Schema 未用于 Parquet 写入
- bash - 是否有一个简单快速的解决方案来比较 bash 中的两个 csv 文件?
- python - 带有 Gunicorn + Eventlet 的 Flask 应用程序的信号处理程序
- node.js - SyntaxError:标识符“__dirname”已被声明
- java - 在客户端和服务器之间发送数据作为字节数组
- symfony - 如何在 Symfony 中持久化 OneToMany 关系数据?
- ios - 使用身体 Alamofire 发布请求