首页 > 解决方案 > 带有 RecyclerView 的 Activity 中的浮动操作按钮未收到 onClick

问题描述

浮动操作按钮上的点击操作不起作用。

我正在学习 android RecyclerView,我能够用数据填充活动。我在活动的底部也有 FloatingActionButton,它不响应触摸事件。尽管侦听器已附加到按钮,但当我点击它时没有任何反应。

活动活动.kt

class EventsActivity : AppCompatActivity() {
    ...

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_events)
        setSupportActionBar(toolbar)

        //MY FAB BUTTON IS ATTACHED WITH LISTENER HERE
        addEvent.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                .setAction("Action", null).show()
        }

        ...

        setupRecyclerAdapter()
    }
}

活动事件.xml

<?xml version="1.0" encoding="utf-8"?>
<layout 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">
    <data>

    </data>
    <androidx.coordinatorlayout.widget.CoordinatorLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context=".events.EventsActivity">

        <com.google.android.material.appbar.AppBarLayout
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android:theme="@style/AppTheme.AppBarOverlay">

            <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="?attr/colorPrimary"
                    app:popupTheme="@style/AppTheme.PopupOverlay"/>

        </com.google.android.material.appbar.AppBarLayout>

        <include android:id="@+id/content_events"
                 layout="@layout/content_events"/>

        <com.google.android.material.floatingactionbutton.FloatingActionButton
                android:id="@+id/addEvent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end|bottom"
                android:layout_margin="@dimen/fab_margin"
                app:srcCompat="@android:drawable/ic_input_add"/>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>

FabGif

标签: androidkotlin

解决方案


addEvent.setOnClickListener(this)

override fun onClick(v: View?)
{
   when(v!!.id)
    {
        R.id. addEvent ->
    {
       Log.i("FABCLICK","Click on Fab icon")
    }

    }
}

推荐阅读