我已經實現了一個ListView加載新聞,但是當我滾動列表時新聞更改位置。這是清單ListView項目更改滾動位置
public class ListNewsFragment extends SherlockListFragment{
private ListNewsAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
mAdapter = new ListNewsAdapter(this, app.getAllNews());
setListAdapter(mAdapter);
super.onCreate(savedInstanceState);
}
}
public class ListNewsAdapter extends BaseAdapter{
private List<News> news;
private Context mContext;
private LayoutInflater inflater;
private ViewHolder holder;
public ListNewsAdapter(final Fragment c, List<News> news) {
super();
this.news = news;
this.mContext = c.getActivity();
inflater = LayoutInflater.from(mContext);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new ViewHolder();
v = inflater.inflate(R.layout.fragment_list_news, null);
holder.name = (TextView) v.findViewById(R.id.tittle);
holder.tweet = (TextView) v.findViewById(R.id.news);
holder.avatar = (ImageView) v.findViewById(R.id.image);
holder.name.setText(news.get(position).getTitulo());
holder.tweet.setText(news.get(position).getCopete());
new ImagefetcherTask(position).execute(holder);
v.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return v;
}
private class ViewHolder{
public TextView name, tweet;
public ImageView avatar;
}
private class ImagefetcherTask extends AsyncTask<ViewHolder, Void, ViewHolder> {
private Bitmap bitmap;
int position;
public ImagefetcherTask(int position) {
this.position = position;
}
@Override
protected ViewHolder doInBackground(ViewHolder... params) {
ViewHolder viewHolder = params[0];
try{
bitmap = BitmapFactory.decodeStream((InputStream) new URL("...."+ news.get(position).getImagen().toString()).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return viewHolder;
}
@Override
protected void onPostExecute(ViewHolder result) {
// TODO Auto-generated method stub
if (bitmap == null) {
result.avatar.setImageResource(com.dev.suma_intranet_v1.R.drawable.img_perfil);
} else {
result.avatar.setImageBitmap(bitmap);
}
}
}
}
只設置文本的TextView當畫面爲空,更好地利用延遲加載加載圖像。也緩存他們,所以你不必下載evertime – Raghunandan
@Raghunandan我應該怎麼做? –
在getView方法中的else語句後移動設置爲文本代碼 –