【问题标题】:Android: ListView add gradient for each rowAndroid:ListView为每一行添加渐变
【发布时间】:2012-01-28 11:41:34
【问题描述】:

我想为每一行添加渐变。我试图做的是在 listview 标签上放置这个属性,android:background="@drawable/mygradient"。但我得到的只是整个列表中显示的渐变。我想要的是为每个项目显示这个渐变。

提前致谢

【问题讨论】:

  • 您是否使用了自定义列表视图?尝试过的代码可能有助于给出答案,发布代码
  • 显示在列表中..这看起来如何?可以发个截图吗?

标签: android listview gradient


【解决方案1】:

您可以为列表视图提供自定义适配器,并在其getView 方法中将渐变设置为背景。像这样的:

public class MyAdapter extends BaseAdapter {
    List<MyDataType> myData;
    Context context;

    public MyAdaptor(Context ctx, List<MyDataType> myData) {
        this.myData = myData;
        this.context = ctx;
    }

    public int getCount() { return myData.size() };
    public Object getItem(int pos) { return myData.get(pos); }
    public long getItemId(int pos) { return 0L; }

    public View getView(int pos, View convertView, ViewGroup parent) {
        //this is where you can customise the display of an individual
        //list item by setting its background, etc, etc.

        ...

        //and return the view for the list item at the end
        return <List item view>;
    }
}

然后您可以将此适配器设置为您列表的适配器:

ListView myList = <initialise it here>
myList.setAdapter(new MyAdapter(getContext(), listData);

现在,当需要显示列表项时,将调用getView 方法,您将在其中执行所有必要的显示自定义,包括设置背景。

【讨论】:

  • 我花了 2 天时间,但到最后我设法做到了。我不习惯自定义适配器,所以很难。无论如何,感谢您的帮助,它非常有用。
  • 一年多过去了,它仍然没有被标记为答案 =/
【解决方案2】:

不设置背景属性设置列表的Selector,如下:

android:listSelector="@drawable/list_selector_background"

【讨论】:

    猜你喜欢
    • 2018-02-04
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多