如何在ListView中的TextView的背景颜色上添加渐变效果?

43

这是一个与编程有关的内容链接,可能会对你有所帮助:https://dev59.com/WXI-5IYBdhLWcg3wxbjv#1683195 - QuokMoon
3个回答

108
你只需要创建一个可绘制资源(看下面的示例),并将其添加到为你的ListItem创建的布局中。
可绘制资源(在你的res\drawable文件夹中 - 可以随意命名 - 例如listgrad.xml)可能如下所示:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
      android:startColor="@color/gradient_start"
      android:endColor="@color/gradient_end"
      android:angle="-270" /> 
</shape>
你需要将其添加到列表项布局中(你为此定义的layout.xml文件),代码片段如下所示:
<TextView
        android:id="@+id/ranking_order"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/list_grad"
        />
...

1
谢谢,但我只想为TextView设置渐变而不是背景。我该怎么做? - saigopi.me
你不能把渐变应用到TextView。顺便说一句,@SaiGopiMe(我看到你的问题已经有3年了,但迟到总比不来得好)。 - Booger
1
@saigopi.me,你可以使用这个库在TextView上应用渐变效果 https://github.com/veeyaarVR/SuperGradientTextView它对我很有用。谢谢。 - Ali Raza
1
呸,为什么要添加第三方库来处理这么简单的事情?我不想在我的应用中增加另一个依赖。 - Booger

11

创建了渐变后,你可以将其应用于几乎任何东西,无论是textView、布局还是按钮。

要了解如何创建和使用渐变,请参考此链接

要创建渐变,你需要将它添加到以下目录中:

enter image description here

渐变的代码可能如下所示 -

<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <gradient
                android:startColor="#ff2d9a59"
                android:centerColor="#ff42959a"
                android:endColor="#ff23729a"
                android:angle="135"/>
        </shape>
    </item>
</selector>

3
从这里引用: 如何在Android中创建带圆角的ListView? (我发现它非常有用。)
将以下内容添加到文件中(比如gradient.xml),然后将其放置在(res/drawable/gradient.xml)目录中。
<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle"> 
     <gradient 
         android:startColor="#SomeGradientBeginColor"
         android:endColor="#SomeGradientEndColor" 
         android:angle="270"/> 

    <corners 
         android:bottomRightRadius="7dp" 
         android:bottomLeftRadius="7dp" 
         android:topLeftRadius="7dp" 
         android:topRightRadius="7dp"/> 
</shape> 

创建完这个文件后,只需通过以下方式之一设置背景:

通过代码:listView.setBackgroundResource(R.drawable.customshape);

通过XML,只需将以下属性添加到容器(例如LinearLayout或任何字段)中:

android:background="@drawable/customshape"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接