在 myadapter.java 我有以下代码:
public View getView(int position,View convertView,ViewGroup parent) {
View view=null;
if(convertView!=null)view=convertView;else view=newView(context,parent);
HashMap<String,String> d=new HashMap<String,String>();
d=data.get(position);
String _r=d.get("r");
String out=d.get("out");
Typeface mf=Typeface.createFromAsset(context.getAssets(),"fonts/mf.ttf");
TextView txt=(TextView)view.findViewById(R.id.c_n);
txt.setText(_r);
txt.setTypeface(mf);
if(out.equals("yes") && !d.get("sid").equals("-1")) {
ImageView imag=(ImageView)view.findViewById(R.id.myimage);
imag.setVisibility(imag.VISIBLE);//This fires sometimes while scroll, while
//I scroll & where I don't need it.
//view.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.c_c));
//^ same as setVisibility.
}
...
return view;
}
当我启动我的应用程序时,此列表正常。但是,当我滚动时,imag.setVisibility(imag.VISIBLE);
有时会在我不需要的地方触发,例如 listview 会生成每个滚动事件。某些 ImageView 变得可见,但在应用程序启动时不可见。
我该如何解决这个问题?
最佳答案
问题是由 convertView
及其用于回收现有 View 的方式引起的。
示例 - 假设您的列表适配器有 20 个项目,但 ListView
只能在屏幕上显示 5 个。当 ListView
滚动时,这 5 个列表项“ View ”将通过作为 convertView
参数传递来重新循环。
一旦设置了 ImageView
的可见性,它将在 convertView
中保持设置。换句话说,如果您不希望它可见,则需要将其设置为 INVISIBLE
或 GONE
...
ImageView imag=(ImageView)view.findViewById(R.id.myimage);
if (d.get("ms").equals("yes") && !d.get("sid").equals("-1")) {
imag.setVisibility(View.VISIBLE);
}
else
imag.setVisibility(View.INVISIBLE); // Or use View.GONE depending on what you need
关于android - 滚动时自定义 ListView 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10839328/