如何在ListView中设置多个项目背景颜色?

时间:2017-09-06 18:46:33

标签: android

我有ListView个约20项。我希望第一,第三和第十项具有黑色背景。我尝试过使用

listView.getChildAt(0).setBackgroundColor(Color.BLACK);

onCreate内,但是当我运行它时应用程序崩溃了。在测试了所有种类之后,我最终创建了一个倒数计时器,它从50毫秒开始倒计时并运行代码onFinish。但现在我的物品回收存在问题。我已经尝试为回收到默认值的项目设置背景颜色,但是当我这样做时,应用程序崩溃了。 我一直在寻找解决方案,但我能找到的只是一些使用选择但我需要3个项目才能有黑色背景。

有没有简单的方法来设置项目的背景颜色而不进行回收?它们不需要在运行时或类似的东西进行更改。

1 个答案:

答案 0 :(得分:0)

编辑:根据你的问题

adapter = new ListAdapter(ListActivity.this , R.layout.custom_list , items);
    listView.setAdapter(adapter);


    public class ListAdapter extends ArrayAdapter <String>{

    public ListAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    public ListAdapter(Context context, int resource, ArrayList<String> items) {
        super(context, resource, items);
    }

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

        View v = convertView;

        if (v == null) {
            LayoutInflater vi;
            vi = LayoutInflater.from(getContext());
            v = vi.inflate(R.layout.itemlistrow, null);
        }
        LinearLayout ll = (LinearLayout)v.findViewById(R.id.ll);
        TextView tv = (TextView)v.findViewById(R.id.tv);

        if (position == 1) {
            ll.setBackgroundColor(Color.BLACK);
            tv.setTextColor(Color.WHITE);
        }
        if (position == 3) {
            ll.setBackgroundColor(Color.BLACK);
            tv.setTextColor(Color.WHITE);
        }
        if (position == 10) {
            ll.setBackgroundColor(Color.BLACK);
            tv.setTextColor(Color.WHITE);
        }
        tv.setText(items.get(position));

        return v;
    }

}

只是为了确保itemlistrow.xml位于

之下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

我现在就帮助你。