这段代码在一个 Activity(或 Fragment)中设置了一个 Toolbar 作为 ActionBar,并为一个 FloatingActionButton 设置了点击事件。点击事件中显示一个 Snackbar,展示一条消息并且没有响应。

setSupportActionBar(binding.appBarMain.toolbar);

        binding.appBarMain.fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, '不知加什么.ing', Snackbar.LENGTH_LONG)
                        .setAction('Action', null).show();
            }
        });

在布局文件中,有一个 TextView 和一个 Button。TextView 的文字居中显示,Button 上显示一个字符串 'dow_img'。Button 设置了一个点击事件 'onClick',当点击 Button 时,会执行名为 'dow_imgone' 的方法。

<?xml version='1.0' encoding='utf-8'?>
<androidx.constraintlayout.widget.ConstraintLayout
     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:layout_height='match_parent'
     android:layout_width='match_parent'
     tools:context='.ui.home.HomeFragment'>

    <TextView
         android:layout_height='wrap_content'
         android:layout_width='match_parent'
         android:layout_marginEnd='8dp'
         android:textAlignment='center'
         app:layout_constraintTop_toTopOf='parent'
         app:layout_constraintStart_toStartOf='parent'
         android:textSize='20sp'
         app:layout_constraintEnd_toEndOf='parent'
         android:layout_marginTop='8dp'
         app:layout_constraintBottom_toTopOf='@id/button'
         android:layout_marginStart='8dp'
         android:id='@+id/text_home' />

    <Button
         android:id='@+id/button'
         android:layout_height='wrap_content'
         android:layout_width='wrap_content'
         android:text='@string/dow_img'
         app:layout_constraintTop_toBottomOf='@id/text_home'
         app:layout_constraintStart_toStartOf='parent'
         app:layout_constraintEnd_toEndOf='parent'
         android:layout_marginTop='8dp'
         android:layout_marginStart='8dp'
         android:layout_marginEnd='8dp'
         app:layout_constraintBottom_toBottomOf='parent'
         android:onClick='dow_imgone'/>
</androidx.constraintlayout.widget.ConstraintLayout>

如果要在点击 Button 时执行 dow_imgone 方法,需要在对应的 Activity(或 Fragment)中实现该方法。例如:

public void dow_imgone(View view) {
    // 在这里执行点击事件的处理逻辑
}
Android Toolbar 设置及 FloatingActionButton 点击事件实现

原文地址: https://www.cveoy.top/t/topic/iXH5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录