gpt4 book ai didi

android - 在适配器 getView 方法中更改当前 ListView 项的背景颜色

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:51:25 25 4
gpt4 key购买 nike

我正在为 ListView 构建自定义适配器 - 我希望此适配器为 ListView 提供交替背景颜色。

boolean alternate = false;

@Override
public View getView(int position, View convertView, ViewGroup parent) {

if (alternate)
{
// set background colour of this item?
}

alternate = !alternate;

// lots of other stuff here

return convertView; }

如何在上下文中设置 ListView 项的背景?

最佳答案

Alternate List item background

下面就是这些步骤来做展示。Step1.1) 对奇数和偶数位置列表项使用两个选择器

artists_list_backgroundcolor.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@color/grey" />
<item android:state_pressed="true"
android:drawable="@color/itemselected" />
<item android:state_selected="true"
android:state_pressed="false"
android:drawable="@color/itemselected" />
</selector>

步骤 1.2)artists_list_background_alternate.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="false"
android:state_pressed="false"
android:drawable="@color/sign_out_color" />
<item android:state_pressed="true"
android:drawable="@color/login_hover" />
<item android:state_selected="true"
android:state_pressed="false"
android:drawable="@color/login_hover" />
</selector>

第二步)颜色.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

<color name="survey_toplist_item">#EFEDEC</color>
<color name="survey_alternate_color">#EBE7E6</color>
<color name="grey">#ffffff</color>
<color name="itemselected">#EDEDED</color>
<color name="login_hover">#E5F5FA</color>
<color name="sign_out_color">#e84040</color>

</resources>

步骤 3) 在 Arrayadapter 中:

    @Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.listitem, parent, false);
}

if (position % 2 == 0) {
view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
} else {
view.setBackgroundResource(R.drawable.artists_list_background_alternate);
}

((TextView) view.findViewById(R.id.heading)).setText(data.get(position));

return view;
}

有关更多详细信息,请访问 belog 链接

http://amitandroid.blogspot.in/2013/03/android-listview-with-alternate-list.html

关于android - 在适配器 getView 方法中更改当前 ListView 项的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18917214/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com