ListView在getView(..)中提供错误的位置值

时间:2015-08-22 08:52:52

标签: android

我对此非常困惑。

问题很简单,我试图调整ImageView高度,为此,我得到显示宽度并添加0.25%的百分比。

问题,如果我在post()ImageView方法之外设置高度的新值,则位置参数在getView()中传递错误。如果我在post()中执行此操作,则显示的第一个元素不会重新缩放。

阅读代码内的评论。

public static class ViewHolder {

        ImageView imgAvatar;

        public void loadAvatar(SocialService socialService, long userId) {

            try {

                // SocialService.loadAvatar(..) is working with UniversalImageLoader.
                socialService.loadAvatar(this.imgAvatar, userId, true, false);
            } catch (Exception ex) {

                Log.e("APPERROR", ex.getMessage());
            }
        }
    }

 @Override
public View getView(int position, View view, ViewGroup parent) {

    ViewHolder holder;

    final User user = this.users.get(position);

    if (view == null) {

        holder = new ViewHolder();

        view = inflater.inflate(R.layout.adapter_list, parent, false);

        holder.imgAvatar = (ImageView) view.findViewById(R.id.people_list_avatar);

        // With this commented snippet of code, the first 4 elements (showed in the top of the listview) are not rescaled.
        // Position is deliver ok.
        // The rest of elements that are going showing while scrolling works pretty fine.
        // If scroll down and come back to the top then the 4 top first elements are showing rescaled.
        /*final ImageView imgAvatarAux = holder.imgAvatar;

        holder.imgAvatar.post(new Runnable() {

            @Override
            public void run() {

                imgAvatarAux.getLayoutParams().height =
                        (int) ((Display.deviceWidth(PeopleAdapter.this.context) / 2) * 1.25F);
            }
        });*/

        view.setTag(holder);

        // HERE IS THE QUESTION.
        // If I remove this line of code, position is deliver ok, but if it works, position is deliver senseless. WHY?
        holder.imgAvatar.getLayoutParams().height = (int) ((Display.deviceWidth(PeopleGridAdapter.this.context) / 2) * 1.25F);

        holder.loadAvatar(this.socialService, user.getId());
    }

    holder = (ViewHolder) view.getTag();

    ...

    if (position == 0) {

        // An interface method for another purposes...
        this.waitFinish.onFinish();
    }

    return view;
}

1 个答案:

答案 0 :(得分:1)

发布ListView项目布局adapter_list。代码修复[对if(){}else{}}之外的列表项的操作:

    // HERE IS THE QUESTION.
    // If I remove this line of code, position is deliver ok, but if it works, position is deliver senseless. WHY?
    holder.imgAvatar.getLayoutParams().height = (int) ((Display.deviceWidth(PeopleGridAdapter.this.context) / 2) * 1.25F);
    view.setTag(holder);

} else {

    holder = (ViewHolder) view.getTag();
}

    holder.loadAvatar(this.socialService, user.getId());