Android 更改特定ListView位置的颜色问题
嘿,我正试图改变listview中特定位置的颜色。我可以改变我想要的位置的颜色,但似乎有一种模式,我想要突出显示的项目列表中的10个位置也被突出显示,我不知道为什么 下面是如何使用颜色更改代码设置my custom adapter.java的Android 更改特定ListView位置的颜色问题,android,arrays,listview,Android,Arrays,Listview,嘿,我正试图改变listview中特定位置的颜色。我可以改变我想要的位置的颜色,但似乎有一种模式,我想要突出显示的项目列表中的10个位置也被突出显示,我不知道为什么 下面是如何使用颜色更改代码设置my custom adapter.java的 package com.example.zach.listview; import android.content.Context; import android.graphics.Color; import android.support.annot
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;
}
}
package com.example.zach.listview;
导入android.content.Context;
导入android.graphics.Color;
导入android.support.annotation.NonNull;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.ArrayAdapter;
导入android.widget.TextView;
类CustomAdapter扩展了ArrayAdapter{
公共CustomAdapter(上下文上下文,字符串[]路由){
超级(上下文、右布局、自定义行、路线);
}
@非空
@凌驾
公共视图getView(int位置、视图转换视图、视图组父视图){
LayoutInflater routeInflater=LayoutInflater.from(getContext());
视图customView=convertView;
如果(customView==null){customView=routeInflater.inflate(R.layout.custom_行,父项,false);}
字符串singleRoute=getItem(位置);
TextView routeText=(TextView)customView.findViewById(R.id.routeText);
routeText.setText(单路由);
//if(getItem(position).equals(“信息”)){
//routeText.setBackgroundColor(颜色为灰色);
//}
如果(位置==0)
{
routeText.setBackgroundColor(颜色为灰色);
}
返回自定义视图;
}
}
这是因为回收。滚动时会重复使用相同的视图。如果为视图设置了值,则必须在else语句中将其重置为默认值,否则当其值被回收时将保持设置状态
列表视图的基本规则-如果您曾经设置过某项内容,请始终设置它。试试这种方法
if(position == 0) {
routeText.setBackgroundColor(Color.GRAY);
} else {
routeText.setBackgroundColor(null); // or any other you want.
}
希望这会有所帮助
愉快的编码。可能重复使用try recyclerview