<?xml version="1.0" encoding="utf-8"?> <!-- 定義基礎的LinearLayout布局 --> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <!-- 定義EditText文本輸入框 --> <EditText android:id="@+id/Et" android:layout_width="fill_parent" android:layout_height="wrap_content" android:hint="請輸入用戶名:"/> <!-- 定義Button按鈕屏幕區域 --> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="myclick" android:text="點擊我,檢測用戶名合法性!"/> <!-- 定義TextView文本標簽 --> <TextView android:id="@+id/Tv" android:layout_width="fill_parent" android:layout_height="fill_parent"/> </LinearLayout>
package com.example.yanlei.yl2; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnKeyListener; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.widget.TextView; import android.widget.EditText; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity { //定義TextView對象 private TextView Tv; //定義EditText對象 private EditText Et; @Override public void onCreate(Bundle savedInstanceState) { //當創建此Activity的時候回調 super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findView(); Et.addTextChangedListener(new EditChangedListener()); } private void findView() { // 得到當前布局的控件對象 Tv = (TextView) findViewById(R.id.Tv); Et = (EditText) findViewById(R.id.Et); } //在xml中綁定的點擊調用函數 public void myclick(View v) { //得到用戶輸入的用戶名,得到長度 int len = Et.getText().toString().length(); //根據輸入的用戶名的長度,做出對應的提示。 if (len > 5 && len < 9) { Tv.setText("用戶名合法,長度為:" + len); } else { Tv.setText("用戶名長度非法,長度為:" + len); } } class EditChangedListener implements TextWatcher { private CharSequence temp="";//監聽前的文本 private int editStart;//光標開始位置 private int editEnd;//光標結束位置 private final int charMaxNum = 10; boolean DEBUG = false; String TAG = "測試:"; @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (DEBUG) Log.i(TAG, "輸入文本之前的狀態"); temp = s; } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (DEBUG) Log.i(TAG, "輸入文字中的狀態,count是一次性輸入字符數"); Tv.setText("還能輸入" + (charMaxNum - s.length()) + "字符"); } @Override public void afterTextChanged(Editable s) { if (DEBUG) Log.i(TAG, "輸入文字后的狀態"); try { if (temp.length() > charMaxNum) { Toast.makeText(getApplicationContext(), "你輸入的字數已經超過10了限制!", Toast.LENGTH_LONG).show(); } } catch (Exception ex) { } } } }