ListView中的Android交替行颜色

ListView中的Android交替行颜色

本文介绍了ListView中的Android交替行颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class ListView extends  ListActivity {

static String item;

public void onCreate(Bundle icicle) {
            super.onCreate(icicle);

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, Str.S);
            setListAdapter(adapter);

      }

这是我的列表视图类,它运行良好,它从名为 Str 的类中获取字符串并将它们显示在列表视图中,问题是列表视图样式不好,它是黑色的,字符串是白色的.

This is my list view class which works nice and it takes the strings from a class called Str and display them in a listview, the problem is the listview style isn't nice, it's black with the strings in white.

我希望它们是可选的,每一行都有一种颜色.

I want them to be alternative each row has a color.

我尝试了很多教程,但都不够清楚..我如何为每一行制作替代颜色......例如.row1 Blue, row 2 White, row 3 Blue, row 4 White, etc..

I tried many tutorials but none was clear enough ..How do I make Alternative Color for each row .. ex. row1 Blue, row 2 White, row 3 Blue, row 4 White, etc..

推荐答案

这里是如何做到这一点.

这里简要给出了我的示例代码:

My example code is given here in brief:

覆盖适配器中的 getView 方法:

Override the getView method in your adapter:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position % 2 == 1) {
    view.setBackgroundColor(Color.BLUE);
} else {
    view.setBackgroundColor(Color.CYAN);
}

return view;
}

覆盖 ArrayAdapter 并覆盖那里的 getView 方法.

Override ArrayAdapter and override getView method there.

所以如果你的适配器是这样的:

So if your adapter is something like this:

public class MyAdapter extends ArrayAdapter

你的 ListActivity 会变成这样:

 ArrayAdapter<String> adapter = new MyAdapter<String>(this,
                android.R.layout.simple_list_item_1, Str.S);

这是一个关于覆盖 ArrayAdapter 的示例.

这篇关于ListView中的Android交替行颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 01:22