更改特定ListView位置问题的颜色

时间:2016-11-10 03:55:27

标签: android arrays listview

嘿所以我试图改变列表视图中特定位置的颜色。我能够改变我想要的位置的颜色,但似乎有一个模式,其中我想突出显示的项目列表中的10个位置也突出显示,我无法找出原因。

下面是如何使用颜色更改代码设置我的自定义adapter.java。

 package com.example.zach.listview;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;


class CustomAdapter extends ArrayAdapter<String>{
public CustomAdapter(Context context, String[] routes) {
    super(context, R.layout.custom_row ,routes);
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater routeInflater = LayoutInflater.from(getContext());
    View customView = convertView;
    if(customView == null){customView = routeInflater.inflate(R.layout.custom_row, parent, false);}

    String singleRoute = getItem(position);
    TextView routeText = (TextView) customView.findViewById(R.id.routeText);

    routeText.setText(singleRoute);

    //if (getItem(position).equals("Information")){
     //   routeText.setBackgroundColor(Color.GRAY);
    //}

    if(position == 0)
    {
        routeText.setBackgroundColor(Color.GRAY);
    }
    return customView;
}
}

2 个答案:

答案 0 :(得分:0)

这是因为回收利用。滚动时会重复使用相同的视图。如果为视图设置了一个值,则必须在else语句中将其重置为default,否则它将在循环时保持设置。

列表视图的基本规则 - 如果您设置了某些内容,请始终进行设置。

答案 1 :(得分:0)

试试这种方式。

if(position == 0) {
    routeText.setBackgroundColor(Color.GRAY);
} else {
    routeText.setBackgroundColor(null); // or any other you want.
}

希望这会有所帮助。

快乐的编码。

相关问题