EditText自訂邊框背景與動態檢測使用者輸入,edittext邊框
一、EditText自訂邊框背景1.效果示範
2.代碼實現
(1)res/drawable/shape_edit_normal.xml功能:編輯框沒獲得焦點時,使用該shape。<shape.../>為根項目的ShapeDrawable資源,主要用於定義一個基本的幾何圖形,如矩形、圓形、線條等。 <solid.../>子項目用於指定填充集合圖形的的顏色; <corners.../>子項目用於定義幾個圖形的四個角的弧度; <gradient../>子項目用於指定填充幾何圖形的漸層顏色; <stroke../>子項目指定幾何圖形邊框線寬度以及顏色; <padding../>子項目指定幾何圖形的內邊框源碼如下:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFFFFF" /> <corners android:radius="4dip"/> <stroke android:width="1dip" android:color="#BDC7D8" /> </shape>
(2)res/drawable/shape_edit_focus.xml源碼如下:編輯框獲得焦點時,使用該shape。與上面的shape區別是,<stroke../>元素的顏色屬性值設定不一致。
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#FFFFFF" /> <corners android:radius="4dip"/> <stroke android:width="1dip" android:color="#728ea3" /> </shape>
(3)res/drawable/selector_edit_frame.xml功能:用於設定檔案編輯框是否有擷取焦點時對應的<shape.../>資源。<selector.../>為根項目的StateListDrawable資源,用於組織多個Drawable對象。當使用StateListDrawable作為目標組件的背景、前景圖片時,StateListDrawable對象所顯示的Drawable對象會隨目標組件狀態的改變自動切換。該元素可以包含多個<item../>子項目,該元素可指定如下屬性: >android:color或android:drawable:指定顏色或Drawable對象; >android:state_xxx:指定一個特定狀態;
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_window_focused="false" android:drawable="@drawable/shape_edit_normal"/> <item android:state_focused="true" android:drawable="@drawable/shape_edit_focus"/></selector>
(4)res/layout/main.xml
...... <EditText android:background="drawable/selector_edit_frame" android:layout_width="match_parent" android:layout_weight="wrap_content"/> ......
二、動態檢測EditText的輸入 在Android項目開發中,往往我們在實現登入或註冊功能時,需要動態來檢測驗證碼框中的內容來決定是否使能登入/註冊按鈕。Android系統提供了一個TextWatch事件監聽器,其可以實現動態檢測EditText輸入情況。
1.效果示範
2.源碼實現功能:動態檢測驗證碼輸入框是否與隨機驗證碼字元匹配,若匹配則使能登入按鈕並改變其背景顏色。
protected void onCreate(Bundle savedInstanceState) { Button loginBtn = (Button)findViewById(R.id.login); EditText secCode = (EditText) findViewById(R.id.login_security_code); secCode.addTextChangedListener(new TextWatcher() { /** *文本編輯框內容未改變前回調該方法 */ public void beforeTextChanged(CharSequence s, int start, int count, int after) { loginBtn.setEnabled(false); // loginBtn.setBackgroundColor(Color.parseColor("#DEB887")); } /** *文本編輯框內容改變時回調該方法 */ public void onTextChanged(CharSequence s, int start, int before, int count) { loginBtn.setEnabled(false); loginBtn.setBackgroundColor(Color.parseColor("#DEB887")); } /** *文本編輯框內容改變後回調該方法 */ public void afterTextChanged(Editable s) { if (secCode.getText().toString().equalsIgnoreCase(verityCode)) { loginBtn.setEnabled(true); loginBtn.setBackgroundResource(R.drawable.selector_btn_background); } } });}