我的自定义列表视图刚刚滚动得不够顺畅,我在本网站上查找的所有解决方案都超出了我的理解范围。非常愿意从之前的问题中解释过的人同样欢迎提供解决方案。这是我的代码:
public class MainActivity extends AppCompatActivity {
String []titles = {"CAPTAIN AMERICA", "DOCTOR STRANGE", "THOR", "SPIDERMAN"};
String []desciption = {"CHRIS EVANS", "BENEDICT CUMBERBATCH", "CHRIS HEMSWORTH", "TOM HOLLAND"};
int []image = {R.drawable.capamerica, R.drawable.doctorstrange, R.drawable.thor, R.drawable.spidey};
ListView lv;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = findViewById(R.id.listview);
MyAdapter adap = new MyAdapter(this, titles, desciption, image);
lv.setAdapter(adap);
}
class MyAdapter extends BaseAdapter {
String []title;
String []desc;
Context context;
int []img;;
LayoutInflater inflater;
public MyAdapter(MainActivity mainActivity, String[] titles, String[] desciption, int[] image)
{
context = mainActivity;
title = titles;
desc = desciption;
img = image;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return title.length;
}
@Override
public Object getItem(int i) {
return i;
}
@Override
public long getItemId(int i) {
return i;
}
public class Info {
ImageView iv;
TextView tv;
TextView tv1;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
Info info = new Info();
View v = inflater.inflate(R.layout.layout, null);
info.iv = v.findViewById(R.id.imgview);
info.tv = v.findViewById(R.id.titlestring);
info.tv1 = v.findViewById(R.id.descriptionstring);
info.iv.setImageResource(img[i]);
info.tv.setText(title[i]);
info.tv1.setText(desc[i]);
return v;
}
}
答案 0 :(得分:1)
使用ViewHolder设计模式: 您的代码在滚动ListView期间经常调用findViewById(),这会降低性能。即使适配器返回一个膨胀的视图以进行回收,您仍然需要查找元素并更新它们。围绕重复使用findViewById()的方法是使用"视图持有者"设计模式。
明确提到了这一点示例:
static class ViewHolder {
private TextView title;
private TextView description;
private ImageView image;
}
ViewHolder holder;
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = inflator.inflate(R.layout.layout, null);
holder = new ViewHolder();
holder.title = (TextView) view.findViewById(R.id.titlestring);
holder.description = (TextView) view.findViewById(R.id.descriptionstring);
holder.image = (ImageView) view.findViewById(R.id.imgview);
view.setTag(holder);
}else {
holder = (ViewHolder) view.getTag();
}
holder.title.setText(titles[position]);
holder.description.setText(description[position]);
holder.image.setImageResource(image[position])
return view;
}
延迟加载图片 实际上,当您滚动列表视图时,每次可见一行时,getView函数都会被触发。因此,如果用户快速上下滚动大型列表视图,则会多次触发getView并且滚动不会平滑。因此建议在单独的线程中执行图像加载,以便平滑滚动列表视图。
另外请确保,您不是创建超过限制的线程。根据用户可见的最大列表项数,建议限制为6-7。
希望它有所帮助。