您好,Stack Overflow Android用户,
请帮助解决以下问题:我正在尝试创建一个列表视图,在某些情况下,某些行的背景颜色会针对不同的视图而改变。这是一些代码。这是MainActivity.class
public class MainActivity extends Activity {
ListView list;
ArrayList<Map<String, String>> values;
String[] names = {"Astor", "Brian", "Cody", "Dexter", "Emma", "Finch", "Glenn"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.list);
values = new ArrayList<Map<String, String>>();
for(int i = 0; i<6; i++){
Map<String, String> map = new HashMap<String, String>();
map.put("id", ""+i);
map.put("title", names[i]);
values.add(map);
}
final mAdapter adapter = new mAdapter(this, R.layout.list1, values);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "itemClick: position = " + position + ", id = " + id, Toast.LENGTH_LONG).show();
}
});
}
这是我的自定义适配器类mAdapter.class:
public class mAdapter extends ArrayAdapter{
private ArrayList<Map<String, String>> values;
public mAdapter(Context context, int textViewResourceId, ArrayList<Map<String, String>> values){
super(context, textViewResourceId, values);
this.values = values;
}
public View getView(int pos, View v, ViewGroup p){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(v == null){
v = inflater.inflate(R.layout.list1, null);
}
TextView t = (TextView) v.findViewById(R.id.title);
t.setText("Position: " + pos);
if(pos == 2){
v.setBackgroundColor(0x30ff0000);
t.setText("!!!Position: " + pos);
}
return v;
}
}
当我运行该应用程序时,会得到以下结果:默认背景色是灰色。如您所见,不仅更改了带有“ pos” 2的行的颜色,而且更改了带有“ pos” 0和5的行的颜色。但是,另一方面,仅更改了带有“ pos”等于2的右行的文本。谁能解释为什么会发生这种情况,以及解决该问题的方法是什么?
谢谢
PS似乎,我没有足够的观点来发表图片。这是结果http://i.stack.imgur.com/4bHeC.png的屏幕截图
在其他情况下,也应将默认颜色设置为灰色
像这样
if(pos == 2){
v.setBackgroundColor(0x30ff0000);
t.setText("!!!Position: " + pos);
}
else {
v.setBackgroundColor(color code for grey);
}
发生这种情况是因为您正在重用转换视图
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句