我正在使用以下代码作为 Android 中 ListView 的 Cusotm Array 适配器
在 View 中新建 MyAsyncTask(url, callback);将一次又一次地运行,我怎样才能使对服务器的查询只执行一次。
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
final Question question = quesions.get(position);
final OpenionUser myUser = question.getUser();
View view = convertView;
ViewHolder viewHolder = new ViewHolder();
if (convertView == null)
{
view = inflator.inflate(R.layout.question_adapter_layout, parent, false);
viewHolder.firstPhotoPercent = (TextView) view.findViewById(R.id.firstPhotoProgressText);
viewHolder.secondPhotoPercent = (TextView) view.findViewById(R.id.secondPhotoProgressText);
viewHolder.comments = (LinearLayout) view.findViewById(R.id.commentsListView);
viewHolder.profilePic = (ImageButton) view.findViewById(R.id.profile);
viewHolder.leftPic = (ImageButton) view.findViewById(R.id.photo1);
viewHolder.rightPic = (ImageButton) view.findViewById(R.id.photo2);
viewHolder.firstPhotoBg = (RelativeLayout) view.findViewById(R.id.firstPhotoProgress);
viewHolder.secondPhotoBg = (RelativeLayout) view.findViewById(R.id.secondPhotoProgress);
view.setTag(viewHolder);
}
else
viewHolder = (ViewHolder) view.getTag();
// //imageLoader.displayImage(myUser.getProfilePicture(), viewHolder.profilePic, options);
//
viewHolder.username.setText(myUser.getUserName());
viewHolder.question.setText(question.getQuestion());
imageLoader.displayImage(question.getRightThumbnailLink(), viewHolder.rightPic, options);
imageLoader.displayImage(question.getLeftThumbnailLink(), viewHolder.leftPic, options);
String url = String.format(Constants.GET_QUESTION_COMMENTS,
question.getId(),
0,
2);
ResponseCallback callback = new ResponseCallback()
{
@Override
public void onSuccess(HttpResponse response)
{
try {
JSONObject obj = new JSONObject(Utilities.convertStreamToString(response.getEntity().getContent()));
JSONArray array = obj.getJSONArray("comments");
ArrayList<Comment> comments = new ArrayList<Comment>();
for (int i = 0; i < array.length(); i ++)
{
Comment comment = Utilities.getCommentFromJSON(array.getJSONObject(i));
comments.add(comment);
}
addFeaturedViews(comments, viewHolder.comments);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(HttpResponse exception)
{
}
};
new MyAsyncTask(url, callback);
最佳答案
“绝对不能保证 getView() 的调用顺序和调用次数”(Romain Guy @ here)。例如,当元素离开屏幕然后在滚动 ListView 后再次出现时调用此方法。所以你不应该从 getView 调用你的服务器:相反,你应该在适配器外部执行你的异步任务(例如,在 fragment 或 Activity 中,在实例化适配器之前),然后在你的列表上调用 notifyDataSetChanged。
关于java - Listview 项目 getView 一次又一次地重复自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17045024/