如何将动态值传递给渐变 xml

How to pass dynamic values to gradient xml

我遇到以下情况:我的 activity 中有渐变背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="90"
        android:endColor="#0F7D71"
        android:startColor="#0E725B"
        android:type="linear" />
</shape>

这是我将此背景设置为 activity 的方式:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/login_gradient_background"
    tools:context=".ui.login.LoginActivity">

但我还需要在其他一些屏幕上使用其他颜色的渐变背景。现在我为每个屏幕创建一个新的渐变文件,但我认为这不是最好的方法。那么,你能帮我解释一下如何从代码中传递颜色,使项目只有一个渐变 xml 吗?提前致谢!

根本不需要使用 XML 文件,您应该从代码创建一个 GradientDrawable 并根据每个屏幕自定义它,然后将其设置为根 [=17] 的背景=] activity 或片段。点击here查看使用方法