gpt4 book ai didi

java - 如何使用 Kotlin 或 Java 更改可绘制对象的描边颜色

转载 作者:行者123 更新时间:2023-12-02 09:39:37 25 4
gpt4 key购买 nike

我有一个可绘制对象,用于设置线性布局的背景,将线性与圆形形状一起留下半透明的橙色线。但在代码中的某个时刻,我需要将此背景(可绘制对象)的颜色更改为我仅作为参数的颜色,而我的颜色文件的颜色中没有它。我需要将此可绘制对象的描边颜色更改为运行时变量之一中的颜色

bg_static_show_password.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<!-- center circle -->
<stroke android:color="@color/accent_color_alpha"
android:width="3dp" />
<solid android:color="@android:color/transparent" />
<size
android:width="28dp"
android:height="28dp"/>
</shape>

线性布局

<android.support.constraint.ConstraintLayout
android:id="@+id/card_show_password"
android:layout_width="@dimen/anim_layout_size"
android:layout_height="@dimen/anim_layout_size"
android:layout_marginTop="@dimen/anim_margin_top"
android:background="@drawable/bg_static_show_password"
android:layout_gravity="center"
app:layout_constraintTop_toBottomOf="@id/view_group_item"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">

我试图用来改变颜色的方法

fun showAlternativeForAnimation(view: LinearLayout) {
val drawable = view.background as GradientDrawable
val theme = PasswordRecoveryTheme(ApplicationSession.instance?.themeId)
drawable.setStroke(1, theme.getAccentColor(ApplicationFactory.context!!))

}

方法参数为LinearLayout

当我尝试时,我收到此异常:kotlin.TypeCastException:null 无法转换为非 null 类型 android.graphics.drawable.GradientDrawable

最佳答案

进行安全转换(as?),确保您传递的 View 具有可绘制形状作为其背景,并将参数更改为view: View,以便允许用于任何 View (LinearLayout、ConstraintLayout 等)。

fun showAlternativeForAnimation(view: View) {
val drawable = view.background as? GradientDrawable
val theme = PasswordRecoveryTheme(ApplicationSession.instance?.themeId)
drawable?.setStroke(1, theme.getAccentColor(ApplicationFactory.context!!))
}

关于java - 如何使用 Kotlin 或 Java 更改可绘制对象的描边颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57203746/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com