我的listView中有3个项目,问题是pointToPosition()方法为列表中的第一个项目返回1,为列表中的第三个项目返回-1。 rawx和rawy位置是正确的,因为它们匹配设备开发工具给出的dX和dY位置。因此,我不能弄清楚如何获得列表项的正确光标位置,尤其是最后一个位置,因为代码返回-1而不是位置2.如果需要,我可以粘贴更多代码
int pos = listView.pointToPosition((int) arg1.getRawX(), (int) arg1.getRawY());
布局
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/x"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.buzz.ContactFragment"
tools:ignore="MergeRootFrame"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ListView
android:id="@+id/contact_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@null"
/>
...
片段
public class ContactFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>,
GestureDetector.OnGestureListener, GestureDetector.OnDoubleTapListener, View.OnTouchListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
gdc = new GestureDetectorCompat(getActivity().getApplicationContext(), this);
View rootView = inflater.inflate(
R.layout.fragment_contact, container, false);
listView = (ListView) rootView.findViewById(R.id.contact_list);
...
}
...
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
int pos = listView.pointToPosition((int) arg1.getRawX(), (int) arg1.getRawY());
Cursor cursor = (Cursor)listView.getItemAtPosition(pos);
...
}
...
答案 0 :(得分:1)
此问题已根据网络上的建议得到解决,但抱歉记不起网址。
public int getTouchPosition(MotionEvent motionEvent){
// Transient properties
int mDismissAnimationRefCount = 0;
float mDownX;
int mDownPosition=-1;
View mDownView=null;
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownPosition = mListView.getPositionForView(mDownView);
}
return mDownPosition;
}
可以使用该位置获取用于填充视图的光标位置
Cursor cursor = (Cursor)mListView.getItemAtPosition(mDownPosition);