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;
            }
        });
4

1 回答 1

4

ListView 正在使用 convertView 回收视图,因此它仅在第一次创建视图时设置 onTouchListener(因为if (convertView == null).

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

于 2012-09-20T06:17:21.367 回答