[英]How to inflate another layout inside getView() of gridview adapter in android?
[英]Android - How to know when getView is called to inflate list
我有一個列表適配器,可以使列表膨脹。 在方法getView()
我創建了一個AscyncTask
以從互聯網獲取圖像。 但是,我發現調用getView()
方法的原因有很多,不僅是為了使列表膨脹。
我的問題是:如何知道何時調用該方法來膨脹列表? 我不想每次調用該方法時都創建一個AsyncTask
。
這是我的代碼:
public class ListItem extends ArrayAdapter<Carro> {
private final Activity context;
private final List<Carro> carros;
public ListItem(Activity context, List<Carro> carros) {
super(context, R.layout.list_item, carros);
this.context = context;
this.carros = carros;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.list_item, null, true);
TextView modelo = (TextView) rowView.findViewById(R.id.modelo);
modelo.setText(carros.get(position).getModelo());
GetFoto getFoto = new GetFoto(rowView);
getFoto.execute(position);
return rowView;
}
private class GetFoto extends AsyncTask<Integer, Void, Void> {
Drawable fotoDraw;
View rowView;
int position;
public GetFoto(View view) {
this.rowView = view;
}
@Override
protected Void doInBackground(Integer... params) {
position = params[0];
HTTPHandler handler = new HTTPHandler();
fotoDraw = handler.makeServiceCallImage(carros.get(position).getFoto());
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
ImageView imagem = (ImageView) rowView.findViewById(R.id.imagem);
imagem.setImageDrawable(fotoDraw);
}
}
}
每次在滾動過程中視圖出現在屏幕上時,都會調用getView()
方法。 如果ListView
高度設置為wrap_content
,則getView()
方法調用的數量可以大於元素的數量。
使用一些庫(例如Picasso
或Glide
下載圖像。 這些庫將緩存下載的圖像,以防止不必要的請求。
它看起來像這樣:
Glide.with(context)
.load(imageUrl)
.into(imageView);
或者您可以閱讀本文https://developer.android.com/topic/performance/graphics/cache-bitmap.html
我建議使用RecyclerView
而不是ListView
。 它回收了防止多次通貨膨脹的觀點
就像亞歷克斯·尼克(Alex Nik)所說:使用畢加索或滑行來加載圖片。 並停止使用ListView,它們已經過時了,但仍然受支持。 使用RecyclerView,它會更好,更容易使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.