【发布时间】:2020-03-06 12:26:09
【问题描述】:
我正在寻找一种解决方案来更改某些 Android Material Components 布局对象的颜色。 如何以编程方式更改材质按钮中文本或边框的颜色? MaterialButton.setTexColor() 等所有功能都不起作用。 StrokeColor 也是如此。必须从逻辑上直接从代码中进行更改。 没有 XML 样式,颜色必须能够根据从数据库读取的值实时更改。
这样的事情是行不通的:
//renewSetDate is a Material Button Object
renewSetDate.strokeColor = ColorStateList.valueOf(Color.RED)
renewSetDate.setTextColor(Color.WHITE)
这是材质按钮的 XML 布局
<com.google.android.material.button.MaterialButton
android:id="@+id/addSubs_btnSet_date"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="15dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="15dp"
android:text="Imposta data di rinnovo abbonamento"
android:textAlignment="center"
android:textColor="#FFFFFF"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/addSubs_detailTitle"
app:strokeColor="@color/colorAccent" />
颜色必须从保存在数据库中的模板中读取。我无法为每个模板创建 XML 样式。
我发现只有通过谁知道 XML 模板中的哪些属性才能更改布局颜色真的很烦人。
这些是依赖项
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.viewpager2:viewpager2:1.0.0-rc01'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
【问题讨论】:
-
你用的是哪个版本?
-
类似
button.setStrokeColor(AppCompatResources.getColorStateList(this, R.color.button_selector));和button.setTextColor(AppCompatResources.getColorStateList(this,R.color.button_selector));的工作。 -
但是我以十六进制数字的形式从数据库记录中读取颜色,例如#A45B01。所以我不能使用 R.color.xxxxxxxx 。我根本不能使用任何 XML 文件,样式或颜色...所有颜色将在运行时插入按钮中,当我打开 Activity 时,但从数据库中读取数据。
-
我认为问题出在库中,并且他们(谷歌开发人员)定义材料对象的属性的方式......我认为我将使用标准对象进行布局点...
-
尝试使用素材库的1.1.0-beta02。
标签: android android-layout android-button android-design-library material-components-android