如果有更好的方法,请告诉我,这可能不是正确的方法。
我创建了一个自定义适配器类,在我的getView方法中填充我想要使用的视图。
public View getView(int position, View convertView, ViewGroup parent)
{
View v = mInflater.inflate(R.layout.wherelayout, null);
if (convertView != null)
{
v = convertView;
}
HashMap<String, Object> whereHash = (HashMap<String, Object>) this.getItem(position);
if (whereHash != null)
{
TextView whereId = (TextView) v.findViewById(R.id.tvWhere);
TextView whereDetails = (TextView) v.findViewById(R.id.tvWhereDetails);
ImageButton ibDelWhere = (ImageButton) v.findViewById(R.id.ibDelWhere);
whereId.setText((CharSequence) whereHash.get("where"));
whereDetails.setText((CharSequence) whereHash.get("details"));
if (ibDelWhere != null)
{
ibDelWhere.setId(position);
ibDelWhere.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
//do stuff when clicked
}
}
);
}
}
return v;
}
这个视图由两个左对齐的TextView和一个右对齐的ImageButton组成。当点击按钮时,我想要能够从ListView中删除该项。布局如下 -
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal" android:clickable="true">
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textSize="25sp" android:id="@+id/tvWhere" android:textColor="#00FF00" android:text="TextView" android:gravity="top|left" android:layout_alignParentTop="true" android:layout_alignParentLeft="true"></TextView>
<TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/tvWhereDetails" android:textColor="#0000FF" android:text="TextView" android:textSize="18sp" android:layout_below="@+id/tvWhere" android:gravity="bottom|left" android:layout_alignParentLeft="true"></TextView>
<ImageButton android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/eraser" android:id="@+id/ibDelWhere" android:layout_alignParentRight="true" android:layout_alignParentTop="true"></ImageButton>
</RelativeLayout>
问题是,当ImageButton位于布局中时,我可以点击它并且onClick()会按预期触发,但是我无法点击实际的列表项本身,即无法点击TextView项目来触发已分配给它的ListView.onItemClick。 如果我从布局中删除ImageButton,则单击项时将触发ListView.onItemClick事件。 有没有办法同时启用单击ListView项目和布局中的按钮? 谢谢大家。