MainActivity如下:
package cc.testpointtoposition; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ListView; import android.widget.SimpleAdapter; import android.app.Activity; /** * Demo描述: * ListView中pointToPosition()方法使用示例. * 依据触摸点的坐标计算出点击的是ListView的哪个Item * * 参考资料: * http://blog.csdn.net/guolin_blog/article/details/17357967 * Thank you very much */ public class MainActivity extends Activity { private ListView mListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); listenListViewTouch(); } private void init(){ mListView=(ListView) findViewById(R.id.listView); List<HashMap<String, Object>> list=new ArrayList<HashMap<String,Object>>(); HashMap<String, Object> hashMap=null; for (int i = 0; i < 8; i++) { hashMap=new HashMap<String, Object>(); hashMap.put("name", "小明"+i); hashMap.put("phone", "135"+i); hashMap.put("amount","500"+i); list.add(hashMap); } SimpleAdapter adapter=new SimpleAdapter(this, list, R.layout.listviewitem, new String []{"name","phone","amount"}, new int[]{R.id.name,R.id.phone,R.id.amount}); mListView.setAdapter(adapter); } private void listenListViewTouch(){ mListView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { int item=mListView.pointToPosition((int) event.getX(), (int) event.getY()); System.out.println("---> 现在点击了ListView中第"+(item+1)+"个Item"); return true; } }); } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center_horizontal" android:text="测试ListView的pointToPosition()方法" /> <ListView android:id="@+id/listView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@id/textView" /> </RelativeLayout>
listviewitem如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="50dip" android:gravity="center" android:orientation="horizontal" > <TextView android:id="@+id/name" android:layout_width="100dip" android:layout_height="wrap_content" /> <TextView android:id="@+id/phone" android:layout_width="150dip" android:layout_height="wrap_content" /> <TextView android:id="@+id/amount" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
时间: 2024-12-18 00:46:18