Android中Button,EditText獲取焦點後點擊事件的觸發
阿新 • • 發佈:2019-01-04
前兩天看了一篇文章,說如果給一個Button設定能夠獲取焦點的屬性後(android:focusableInTouchMode="true"),那麼第一次點選這個按鈕的話,並不會觸發點選事件,接下來繼續點選才會觸發點選事件.由於在學習的過程中並沒有遇到過這種情況,所以立馬寫了一個Demo測試.
最開始的Demo是這樣的:
<Button
android:id="@+id/btn"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕"
android:layout_gravity="center_horizontal"/>
然後執行,點選按鈕,彈出Toast,和往常並沒有區別.當時很奇怪,並不像文章中說的那樣,於是又仔仔細細從頭到尾看了一遍,然後寫了第二個Demo測試.
第二次的Demo是這樣的:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="輸入框"
/>
<Button
android:id="@+id/btn"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕"
android:layout_gravity="center_horizontal"/>
執行之後,進入介面,首先是EditText拿到焦點(EditText預設是能獲取焦點的),輸入法彈出,一切正常.然後點選按鈕,輸入法消失,點選事件沒有觸發,再點選一次,點選事件觸發.
然後我把上述程式碼中的android:focusableInTouchMode="true"刪掉,再次進行測試發現,點選按鈕會立馬觸發點選事件,並不會讓鍵盤消失.
事實證明,在第一個Demo中,只有一個Button的情況下,而且它有獲取焦點的能力,所以第一次執行後它就已經拿到了焦點,然後點選的話就直接觸發點選事件.在第二個Demo中,在它的上面有一個EditText,所以EditText先拿到焦點,然後第一次點選Button就是切換了焦點,第二次點選才觸發點選事件.
在這裡還有一個特別需要注意的地方就是,如果把EditText放在下面的話,先拿到焦點還是Button,執行後不會立馬彈出鍵盤.
最開始的Demo是這樣的:
<Button
android:id="@+id/btn"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕"
android:layout_gravity="center_horizontal"/>
然後執行,點選按鈕,彈出Toast,和往常並沒有區別.當時很奇怪,並不像文章中說的那樣,於是又仔仔細細從頭到尾看了一遍,然後寫了第二個Demo測試.
第二次的Demo是這樣的:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:hint="輸入框"
/>
<Button
android:id="@+id/btn"
android:focusableInTouchMode="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="按鈕"
android:layout_gravity="center_horizontal"/>
執行之後,進入介面,首先是EditText拿到焦點(EditText預設是能獲取焦點的),輸入法彈出,一切正常.然後點選按鈕,輸入法消失,點選事件沒有觸發,再點選一次,點選事件觸發.
然後我把上述程式碼中的android:focusableInTouchMode="true"刪掉,再次進行測試發現,點選按鈕會立馬觸發點選事件,並不會讓鍵盤消失.
事實證明,在第一個Demo中,只有一個Button的情況下,而且它有獲取焦點的能力,所以第一次執行後它就已經拿到了焦點,然後點選的話就直接觸發點選事件.在第二個Demo中,在它的上面有一個EditText,所以EditText先拿到焦點,然後第一次點選Button就是切換了焦點,第二次點選才觸發點選事件.
在這裡還有一個特別需要注意的地方就是,如果把EditText放在下面的話,先拿到焦點還是Button,執行後不會立馬彈出鍵盤.