android 控制元件按下與鬆開事件
阿新 • • 發佈:2019-02-02
最近公司新開了一個專案,之前的專案做完也沒有做過記錄,很多東西都找不到了,為了以後能夠方便查閱專案資料,還是寫一下部落格記錄一下吧。
之前做的專案中使用者登入模組都是用的驗證碼以及第三方登入,這次BOSS要求使用者名稱密碼登入,功能設計密碼可見與不可見,只能重新寫登入模組了。
密碼的可見與不可見是很好實現的, EditText提供了方法去設定:
設定密碼可見
edtLoginPw.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
設定密碼不可見 edtLoginPw.setTransformationMethod(PasswordTransformationMethod.getInstance());
但是,總得要有條件去觸發執行這些方法吧,於是密碼輸入框後有了一個小眼睛似的圖示來提醒使用者點選可以檢視密碼,圖示在按下與鬆開時切換圖示顯示
程式碼:
imgShowLoginPwd.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_UP://鬆開事件發生後執行程式碼的區域 Log.e(TAG,"密碼不可見"); imgShowLoginPwd.setImageResource(R.drawable.icon_pwd_hind); edtLoginPw.setTransformationMethod(PasswordTransformationMethod.getInstance()); break; case MotionEvent.ACTION_DOWN://按住事件發生後執行程式碼的區域 Log.e(TAG,"密碼可見"); imgShowLoginPwd.setImageResource(R.drawable.icon_pwd_show); edtLoginPw.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); break; default: break; } return true; } });
注意 onTouch方法中返回值應修改為true 否則當前圖示的按壓事件中只能消費MotionEvent.ACTION_DOWN事件,而MotionEvent.ACTION_UP事件將不消費,
你的圖示只能顯示為按下後的樣子,鬆開後也不會恢復
如果不需要監聽事件,那麼只需要自己寫一個xml檔案,將其設定為相應控制元件的背景即可。
控制元件:
xml檔案:btn_commit<Button android:layout_width="match_parent" android:layout_height="@dimen/btn_commit_height" android:textSize="@dimen/text_size_18" android:layout_marginTop="20dp" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" style="?android:borderlessButtonStyle" android:background="@drawable/btn_commit" android:text="提交"/>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_commit_02" android:state_pressed="true"/>
<item android:drawable="@drawable/btn_commit_01" android:state_pressed="false"/>
<item android:drawable="@drawable/btn_commit_01"/>
</selector>
btn_commit_01與btn_commit_02就是你自己寫的按下與鬆開的兩種樣式了