获取视图显示错误位置 - ListView Android

3

这是我的源代码。getView显示了错误的位置。我已经在谷歌上搜索了解决方案,但没有成功。请帮助我。

public View getView(final int position, View convertView,
        ViewGroup viewGroup) {
    final Phonebook entry = listPhonebook.get(position);
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.phone_row, null);
        convertView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View mycurrentListItemView,
                    MotionEvent event) {

                int action = event.getAction();
                if (action == MotionEvent.ACTION_DOWN) {
                    Log.i("List item clicked position : ", "" + position);
                    Log.i("Name::Mail", "" + entry.getName() + " :: "
                            + entry.getMail());
                    mycurrentListItemView.setBackgroundColor(Color
                            .parseColor("#38ACEC"));
                } else if (action == MotionEvent.ACTION_UP
                        || action == MotionEvent.ACTION_CANCEL) {
                    mycurrentListItemView.setBackgroundColor(Color
                            .parseColor("#FFFFFF"));
                }
                return false;
            }
        });
1个回答

4

ListView 通过 convertView 回收视图,因此只在创建视图时设置一次 onTouchListener(因为有 if (convertView == null))。

如果您希望此解决方案起作用,则必须将 convertView.setOnTouchListener() 调用移动到 if (convertView == null) 条件之外。这样每次在屏幕上显示您的正确电话簿条目时都会初始化它。


1
我也遇到了同样的问题,这条评论帮助了我,谢谢!(+1) - Adam Varhegyi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接