首页 > 解决方案 > 当我单击没有项目的 ListView 时是否有事件?

问题描述

我基本上想在单击没有项目的 ListView 时做一些事情,所以我不想使用 ListView.ItemClick 事件处理程序。当我尝试使用 ListView.Click 时,它告诉我必须使用项目单击。有什么帮助吗?我以这种方式尝试了卢卡斯的解决方案:

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/lvQueue"/>
<ListView.GestureRecognizers>
    <TapGestureRecognizer
        Tapped="OnTapGestureRecognizerTapped"
        NumberOfTapsRequired="1"/>
</ListView.GestureRecognizers>

也是这样:

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/lvQueue">
    <ListView.GestureRecognizers>
    <TapGestureRecognizer
        Tapped="OnTapGestureRecognizerTapped"
        NumberOfTapsRequired="1"/>
</ListView.GestureRecognizers>
    </ListView>

标签: androidlistviewxamarineventsxamarin.android

解决方案


您可以TapGestureRecognizer在 ListView 上添加

以 XML 格式

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/lvQueue"/>

在后面的代码中

ListView listView = FindViewById<ListView>(Resource.Id.lvQueue); ;
listView.SetOnTouchListener(new GestureListener());

public class GestureListener : Java.Lang.Object, View.IOnTouchListener
{
    public bool OnTouch(View v, MotionEvent e)
    {

        // do something you want

        return true;
    }
}

更新

因为 touch 事件总是在 item click 动作之前被调用,所以如果你只想在 itemListView很少的时候在页面的空白处添加 click 事件。我们可以在列表视图下方定义另一个视图,并将点击事件设置为解决方法。

在xml中

将 ListView 放入 LinearLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main">



        <ListView
        android:id="@+id/listView"
        android:background="@android:color/holo_blue_light"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
            />

    <TextView
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_weight="1"   // set the weight as 1 , so that it will warp the white space of the screen auto
         android:background="@android:color/holo_blue_light"  // set the background color the same with thelistview
         android:id="@+id/view"/>



</LinearLayout>

在后面的代码中

TextView view = FindViewById<TextView>(Resource.Id.view);
view.Click += View_Click;
private void View_Click(object sender, EventArgs e)
{
  //...          
}

推荐阅读