嘿,我想改变列表视图中特定位置的颜色。我可以改变我想要的位置的颜色,但似乎有一种模式,从我想要高亮显示的项目的列表中向下10个位置也高亮显示,我不知道为什么。
下面是我的自定义适配器.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;
}
}
这是因为回收。滚动时重用相同的视图。如果你为视图设置了一个值,你必须在else语句中将其重置为默认值,否则当它被回收时,它将保持设置。
列表视图的基本规则——如果你要设置什么,一定要设置。
试试这个方法
if(position == 0) {
routeText.setBackgroundColor(Color.GRAY);
} else {
routeText.setBackgroundColor(null); // or any other you want.
}
希望对你有帮助。
快乐编码。