我试图创建具有不同类别的应用程序,每个类别它有一组图片,我从第一个类别开始(10个图像)工作正常,但当我移动到另一个类别我的应用程序运行缓慢。我正在使用GridView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ArrayList<String> movieList = new ArrayList<>();
movieList.add("https://scontent-waw1-1.xx.fbcdn.net/v/t1.0- 9/18199348_430451573995024_7473960282002692779_n.jpg?oh=8667ffcd3ccb66892fcf4e7330f24e61&oe=59B88B8F");
View v = inflater.inflate(R.layout.fragment_art, container, false);
myGrid= (GridView) v.findViewById(R.id.gridViewCategory);
adapter =new CategoryAdapter(getActivity(),movieList);
myGrid.setAdapter(adapter);
return v;
}
}
class CategoryAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> imageId=new ArrayList<String>();
CategoryAdapter(Context context,ArrayList<String> imageId){
this.context=context;
this.imageId=imageId;
}
@Override
public int getCount() {
return imageId.size();
}
@Override
public Object getItem(int position) {
return imageId.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
class ViewHolder{
ImageView CategoryImage;
ViewHolder(View view){
CategoryImage = (ImageView) view.findViewById(R.id.cat_imageView);
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row=convertView;
ViewHolder holder=null;
if(row == null){
LayoutInflater inflater= (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.picture_item,parent,false);
holder = new ViewHolder(row);
row.setTag(holder);
}
else{
holder=(ViewHolder) row.getTag();
} Glide.with(context).load(imageId.get(position)).placeholder(R.drawable.load).int o(holder.CategoryImage);
return row;
}
}
答案 0 :(得分:1)
AsyncTasks是你的关键!
//使用AsyncTask在后台线程中加载慢图像
new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;
@Override
protected Bitmap doInBackground(ViewHolder... params) {
v = params[0];
return mFakeImageLoader.getImage();
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (v.position == position) {
// If this item hasn't been recycled already, hide the
// progress and set and show the image
v.progress.setVisibility(View.GONE);
v.icon.setVisibility(View.VISIBLE);
v.icon.setImageBitmap(result);
}
} }.execute(holder);
或者您可以在gridview上启用快速滚动。此外,如果要切换到网格的新视图,则可以回收不需要的位图。
如果这些没有帮助,那么尝试使用像Glide这样的库。
希望这有帮助!