【问题标题】:How can I add gradient effect to background color of TextView in a ListView?如何在 ListView 中为 TextView 的背景颜色添加渐变效果?
【发布时间】:2012-12-31 03:19:15
【问题描述】:

关于这些问题:

Adding gradient effect to TextView in a ListView generates NPE

How to change color and font on ListView

我想知道如何在带有渐变效果的ListView 中设置TextView 的背景?

在上面的一个问题中,我最终在TextView 的文本中添加了渐变效果。浏览第二个问题后,我似乎只能添加固定的背景颜色。

如何为背景添加渐变?我应该发CustomListAdapter吗?

【问题讨论】:

标签: android gradient textview


【解决方案1】:

您只需要创建一个可绘制资源(参见下面的示例),并将其添加到您为 ListItem 创建的布局中。

drawable(在您的 res\drawable 文件夹中 - 随便命名 - listgrad.xml for ex)可能如下所示:

<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 文件),如以下代码 sn-p:

<TextView
        android:id="@+id/ranking_order"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/list_grad"
        />
...

【讨论】:

  • 谢谢,但我只想要 textview 的渐变而不是背景。我该怎么办?
  • 你不能将渐变应用到 TextView FWIW,@SaiGopiMe(我看到你的问题已经 3 年了,但迟到总比永远好)。
  • @saigopi.me,您可以使用此库在 textview github.com/veeyaarVR/SuperGradientTextView 上应用渐变,这对我有用。谢谢
  • 哎呀,你为什么要添加一个 3rd 方库来处理这么简单的事情?我不希望我的应用程序中出现其他依赖项。
【解决方案2】:

创建渐变后,您可以将其应用于几乎任何东西,例如 textView、布局或按钮。

要了解如何创建和使用渐变,请参阅this link

要创建渐变,您需要将其添加到以下目录

渐变的代码是这样的 -

<?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】:

    从这里引用:How do I create a ListView with rounded corners in Android? (我发现它非常有用。)

    将以下内容添加到文件中(比如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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 2022-12-21
      相关资源
      最近更新 更多