我想为每一行添加渐变。我试图做的是在 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/