Android:ListView为每一行添加渐变

标签 android listview gradient

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

提前致谢

最佳答案

您可以为 ListView 提供自定义适配器,并在其 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 方法,您将在其中执行所有必要的显示自定义,包括设置背景。

关于Android:ListView为每一行添加渐变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9044974/

相关文章:

android - 在调用适配器的 OnClickListener 期间关闭 AlertDialog

android - Android工具栏和 fragment 背景如何使用一种渐变颜色

ios - iOS Google Maps SDK 中具有跨宽度渐变的折线

java - 如何在 Recyclerview/Layoutmanager 中获取 Scrollposition?

android - 将图像加载异步任务转换为 rxjava,为什么它滞后于 ui?

android - 将数据解析为数组

android - 如何避免 ListView 闪烁 @android :id/empty before loading data. 设置的 View

ios - UIImageView 中的渐变/阴影,如 Flipboard

android - 权限 - android.permission.WRITE_EXTERNAL_STORAGE PlayStore

java - 安卓 View 布局。让 View 填充 View 之间的空间