您的位置:首页 > 移动开发 > Android开发

Android在ListView的onTouch事件中获取选中项的值

2015-04-06 22:53 363 查看
在Android开发中经常使用ListView,最近使用ListView***一个仿QQ的滑动删除控件时遇到一个问题,就是使用ListView的onTouch事件无法获取选中项的值,讲过一番思考和在网上看的一些资料,想到一个解决办法。

ListView listView = (ListView) findViewById(R.id.listView1);
        listView.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO 自动生成的方法存根
				int position = ((ListView)v).pointToPosition((int)event.getX(), (int)event.getY());
				System.out.println(position);
				return false;
			}
		});


使用函数pointToPosition,参数是触摸ListView的横纵坐标。pointToPosition的详情可查看源代码。

/**
     * Maps a point to a position in the list.
     *
     * @param x X in local coordinate
     * @param y Y in local coordinate
     * @return The position of the item which contains the specified point, or
     *         {@link #INVALID_POSITION} if the point does not intersect an item.
     */
    public int pointToPosition(int x, int y) {
        Rect frame = mTouchFrame;
        if (frame == null) {
            mTouchFrame = new Rect();
            frame = mTouchFrame;
        }

        final int count = getChildCount();
        for (int i = count - 1; i >= 0; i--) {
            final View child = getChildAt(i);
            if (child.getVisibility() == View.VISIBLE) {
                child.getHitRect(frame);
                if (frame.contains(x, y)) {
                    return mFirstPosition + i;
                }
            }
        }
        return INVALID_POSITION;
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: