Android:在listfragment中单击listview外部

时间:2017-03-12 19:13:30

标签: java android listview onclicklistener

我有一个listview占据了布局理论的所有空间,但实际上它只占用了布局的一半,因为它只有5个元素,并没有覆盖所有的屏幕。当我触摸列表视图的外部时,我想知道。我尝试为包含列表的listfragment的布局创建一个clicklistener方法,但它永远不会被使用,因为在理论中listview占用了所有布局,因此找不到单击。对活动的布局或多或少都是一样的。在这种情况下,只能在边缘找到点击,所以我找不到解决问题的方法。

这是片段布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@android:id/list" />

以下是活动布局:

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.utente.actionbar.MainActivity">

<Button
    android:text="MULTI"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="26dp"
    android:id="@+id/button" />

<Button
    android:text="SINGOLO"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button"
    android:layout_alignLeft="@+id/button"
    android:layout_alignStart="@+id/button"
    android:layout_marginBottom="25dp"
    android:id="@+id/button2" />

2 个答案:

答案 0 :(得分:2)

  

在理论中,listview占据了所有布局

不是理论,这正是发生的事情;通过使用android:layout_height="match_parent",视图将始终采用全屏高度。

listView.setOnClickListener如果您想查看ListView中的 ,您通常会想要{{1}看你是否点击了任何一个项目,而不是整个列表。

参考:difference between onClickListener and onItemClickListener

如果你真的想缩小listView.setOnItemClickListener,那么ListView是一个选项,但是我不确定是否在内容包装被应用后没有内容实际加载到该视图中在通货膨胀时间,由于没有适配器设置,因此无法完成。

如果你需要在ListView&#34;之外的字面上检测一个监听器,那么你需要在该Fragment的android:layout_height="wrap_content"上设置某种类型的点击/触摸监听器。

rootView

答案 1 :(得分:2)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" <!-- Or specific height -->
    android:id="@android:id/list" />

<View 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/clickView" />

</LinearLayout>

在Fragmet中

public View onCreateView(...) {
    rootView = inflater.inflate(...);
    View clickView = rootView.findViewById(...);
    clickView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // Do something here
    }
});


    return rootView;
}

我想这可以解决你的问题。