我有一个ListView
与CustomAdapter
,我可以改变点击线的颜色。 但我需要改变颜色时,用户要求的答案(这是一个测验应用程序),我试图设置一个公共的方法来调用它从我的MainActivity
,但我得到了一个错误。如何在ListView android中更改特定的行/行颜色?
MyCustomAdapter代码:
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.row_item, null);
lista = parent;
holder.tv=(io.github.kexanie.library.MathView) rowView.findViewById(R.id.texto);
holder.row=(RelativeLayout) rowView.findViewById(R.id.row);
holder.img=(ImageView) rowView.findViewById(R.id.imagem);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
holder.tv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
holder.tv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
holder.tv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
holder.tv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
rowView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//Paint the clicked line, and remove color from the unclicked lines.
for (int j = 0; j < 5; j++) {
parent.getChildAt(j).setBackgroundResource(R.color.branco);
if (j != position) {
status[j] = false;
}
}
if(!status[position]) {
holder.row.setBackgroundResource(R.color.azul);
status[position] = true;
respostas = ((MyApplication) simulado.getApplication()).getRespostas();
mudarAlternativa(position);
}else{
holder.row.setBackgroundResource(R.color.branco);
status[position] = false;
mudarAlternativa(5);
}
}
});
return rowView;
}
画一条线,我用parent.getChildAt(position).setBackgroundResource(R.color.mycolor);
和它的作品,但我想用一个方法把它漆成:
public void paintAnswer(int answerPosition){
parent.getChildAt(j).setBackgroundResource(R.color.green);
}
,但我不能使用parent
,所以我初始化了ViewGroup lista;
并在getView
上设置lista
。 lista = parent
。所以我尝试:在适配器
公共方法:
public void paintAnswer(int answerPosition){
lista.getChildAt(j).setBackgroundResource(R.color.green);
}
从我的MainActivity调用:
adapter.paintAnswer(2);
和我得到一个埃罗。 “由于:java.lang.NullPointerException:尝试调用虚拟方法'android.view.View android.view.ViewGroup.getChildAt(int)'在空对象引用上”。
我如何参考parent
getView
以外使用公共方法绘制线条?
谢谢。我对这方面很了解,你能告诉我一个小例子吗?一个链接,类似的问题等? –
我对你所说的有所了解,而且我将ListView更改为五个LinearLayout,并且它更容易操作。 –
@GLAPPsMobile,如果你有一个固定数量的视图,使用预定义的视图集合而不是'ListView'是有意义的。 –