我有一个列表视图,在这个列表视图的适配器中我有一个方法
public void onItemClick(AdapterView<?> AdapterView, View View,
int position, long id)
列表每行包含3个视图
xml for行
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:background="@android:color/white" android:padding="5dp">
<TextView android:id="@+id/name" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20dp" android:textStyle="bold" android:textColor="@android:color/black"
android:layout_marginTop="10dp" android:focusable="false">
</TextView>
<TextView android:id="@+id/street"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_below="@id/name"
android:textColor="@android:color/black" android:focusable="false">
</TextView>
<ImageView android:id="@+id/pic" android:src="@drawable/pic"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_alignParentRight="true" android:layout_marginRight="10dp"
android:layout_below="@id/name" android:focusable="false">
</ImageView>
</RelativeLayout>
在OnItemClickMethod中,我想找到这3个视图上的单击事件。我该怎么做呢?
注意:如果我使用view.getId()它返回-1的第一行。所以我不能使用这个
if(view.getId() == R.id.name){
dotask();
}
更新:我只是在getView方法中调用onClick方法
setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(context,position.toString(), Toast.LENGTH_LONG).show();
}
});
,我的问题就解决了。
谢谢FunkTheMonk和Vikky.
这里的onItemClick View指的是RelativeLayout而不是textviews,根据你的xml文件
public void onItemClick(AdapterView<?> AdapterView, View View, int position, long id) {
TextView name = View.findViewById ( R.id.name );
for other views .......
}
您可以在ListView中使用的行中为视图设置onClickListener
abstract class Clicker implements OnClickListener {
int mPosition;
public Clicker(int position) {
mPosition = position;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
//inflate
}
//do your stuff
convertView.findViewById(R.id.button1).setOnClickListener(new Clicker(position) {
public void onClick(View v)
{
int row = mPosition;
//button 1 clicked
}
});
convertView.findViewById(R.id.button2).setOnClickListener(new Clicker(position) {
public void onClick(View v)
{
int row = mPosition;
//button 2 clicked
}
});
}
onItemClick只给出被选中的行,并且不提供触摸坐标,所以你不能手动确定哪个子节点被点击了
可以使用view。在onItemClick中获取的视图上的findViewById。这里(http://www.vogella.de/articles/AndroidListView/article.html)说这是一个相对较长的操作,推荐的方法是使用视图的标记来存储其相关的子视图。这似乎合乎逻辑,但在您的情况下,这可能是过早的优化-取决于您的视图的使用数量。