【问题标题】:Set color gradient to shape drawable in XML directly [duplicate]直接在XML中将颜色渐变设置为可绘制的形状[重复]
【发布时间】:2019-08-12 15:03:21
【问题描述】:

我有以下

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >


    <corners android:radius="20dp"/>
</shape>

我将其设置为布局的背景。

我可以使用以下设置颜色

root.getBackground().setColorFilter(Color.parseColor("#ab2233"), PorterDuff.Mode.SRC_ATOP);

但是,这会设置纯色。我想改为设置渐变颜色,然后将此颜色传递给其他背景。 有没有办法设置渐变? 我知道有一个使用画布的 SO 解决方案,但我希望避免它,特别是我想保留圆角和任何其他形状特征。

有没有办法动态设置颜色渐变?我考虑过在形状中引入渐变,但我需要颜色是动态的。

有什么解决办法吗?

谢谢

编辑: 这不是重复的,因为我特别要求继续使用 xml,而只是调整颜色值

【问题讨论】:

  • 我认为除了使用 xml 来设置半径之外,您还可以按照 yvette 的建议以编程方式执行此操作..

标签: android


【解决方案1】:

在xml中添加这个

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:endColor="@color/colorPrimary"
        android:startColor="@color/white" />

    <corners android:radius="20dp"/>
</shape>

或将其添加到 .java 文件中

 View layout = findViewById(R.id.mainlayout);

GradientDrawable gd = new GradientDrawable(
        GradientDrawable.Orientation.TOP_BOTTOM,
        new int[] {0xFF616261,0xFF131313});
gd.setCornerRadius(0f);

layout.setBackgroundDrawable(gd);

【讨论】:

  • xml 设置预定颜色。我需要在运行时动态设置它们,因为颜色是随机的。 java解决方案完全替代了xml。我希望保留 xml 并根据我的问题调整事物的颜色部分
【解决方案2】:

在 /res/drawable 中创建 background.xml:

    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#FFFFFF"
        android:endColor="#00000000"
        android:angle="45"/>    
</shape>

在 /res/layout 中的布局文件中:

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background"
    >   
</LinearLayout>

您可以使用其他功能,如半径、填充等。

并以编程方式显示如下

View layout = findViewById(R.id.mainlayout);

GradientDrawable gd = new GradientDrawable(
        GradientDrawable.Orientation.TOP_BOTTOM,
        new int[] {0xFF616261,0xFF131313});
gd.setCornerRadius(0f);

layout.setBackgroundDrawable(gd);

【讨论】:

  • java代码是xml的替代品。我想保留我的 xml 并在 java 中更改颜色。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-01
  • 2020-08-04
  • 1970-01-01
相关资源
最近更新 更多