当按钮在列表中时,ListView长按不起作用

时间:2014-01-05 09:48:32

标签: android android-listview event-handling onitemclicklistener

我有一个带有自定义列表适配器的ListView。它有OnItemClickListener和OnItemLongClickListner,以前工作正常。之后,我不得不在列表项的布局中放置一个按钮,并且项目单击并且长按监听器停止工作。这是我的示例代码:

ListView lv=(ListView)findViewbyId(R.id.listview); 
lv.setAdapter(listviewadapter);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view,int position, long id) {
            // My code
            }
});

在列表项的布局中添加按钮之前,以前工作正常:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" 
    android:padding="2dp"
    >
    <TextView
        android:id="@+id/symbol_name"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2.5"
        android:layout_gravity="left"
        />
    <TextView
        android:id="@+id/ltp"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="1"
        />
    <TextView
        android:id="@+id/change_in_perc"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="1"
        />

    <TextView
        android:id="@+id/volume"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="1"
        />

    <ImageButton
        android:id="@+id/chart"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="0.5"
        android:src="@drawable/charts"
        android:contentDescription="Chart Link"
        />
</LinearLayout>

我尝试将内联侦听器更改为在活动上实现onItemLongClickListener但直到现在都没有成功。感谢。

2 个答案:

答案 0 :(得分:13)

单击列表项时,您的图像按钮可能会聚焦。

所以添加这个

android:descendantFocusability="blocksDescendants" 

到你的根元素

http://developer.android.com/reference/android/view/ViewGroup.html#attr_android:descendantFocusability

机器人:descendantFocusability

Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.

Must be one of the following constant values.

Constant    Value   Description
beforeDescendants   0    The ViewGroup will get focus before any of its descendants.
afterDescendants    1    The ViewGroup will get focus only if none of its descendants want it.
blocksDescendants   2    The ViewGroup will block its descendants from receiving focus.
This corresponds to the global attribute resource symbol descendantFocusability.

答案 1 :(得分:0)

你在xml和listview.setLongClickable(true)中设置了android:longClickable =“true”吗?在代码?