iT邦幫忙

2021 iThome 鐵人賽

DAY 12
0
自我挑戰組

Android 初新者系列 第 12

Day12 - Button(二)

我們昨天講到
按鈕事件有分很多種
1.點擊一下事件
2.長按事件
上一篇我們已經學會了按鈕的點擊一下事件
今天我們要更進階一咪咪
來學第2個按鈕的事件
按鈕長按事件
長按這功能也很常用的到
比如:計算機長按歸零、長按預覽訊息
這些都是常按的範疇
那我們廢話不多說

開始

今天我們一樣搭配Log來驗證長按功能是否正確

  • 布局的方面與昨天一樣拉一個按鈕出來
    按鈕文字要打什麼都可以,我這邊就直接打長按
    id也順便設定好,我設跟昨天一樣btn_1
    https://ithelp.ithome.com.tw/upload/images/20210918/20141769p33CDNDVCt.png
<?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_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="158dp"
        android:layout_marginTop="237dp"
        android:layout_marginEnd="159dp"
        android:text="長按"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • 新增按鈕長按的事件
    跟昨天一樣宣告Button,抓元件
    不一樣的就是setOnClickListener事件
    改成setOnLongClickListener事件
    以及
    把Log.v("one","點一下")的內容改成Log.v("one","長按")
Log.v("one","長按" );

https://ithelp.ithome.com.tw/upload/images/20210918/20141769S5dEPNobjE.png

執行結果:
你會發現按一下沒有反應,要按住不放Logcat才會顯示one : 長按
https://ithelp.ithome.com.tw/upload/images/20210918/201417692YyW96okVp.png


上一篇
Day11 - Button(一)
下一篇
Day13 - Button(三)
系列文
Android 初新者30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言