Android TextWatcher的使用方法(監聽ExitText的方法)


我做了一個查詢單詞的簡單app, 當在EditText中輸入單詞的時候,點擊lookup,則在TextView區域顯示出該單詞的意思,當EditText中沒有任何字符時,顯示"word definition result", 注意,單詞的最大長度限制是20個字符,且禁止回車鍵(換行鍵);

這個里面需要用到讀文件操作、禁止鍵盤回車鍵、Textwatcher監聽、限制輸入長度、提示語等操作!

1.   首先需要一個Lookup的button, 一個可以輸入字符的EditText 和一個顯示單詞結果的TextView;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.chenye.dictionary.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/wordEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="input a word"
            android:maxLength="20"
            android:singleLine="true"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="lookup"
            android:onClick="lookup"/>

    </LinearLayout>

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="word definition result"
        android:textSize="20dp"/>

</LinearLayout>

其中android:singleLine="true"為禁止虛擬鍵盤的操作; android:maxLength="20"為限制最大長度;android:hint="input a word"為提示語;這里EditText和button部分是水平布局,而它倆與TextView顯示結果區域是垂直布局;

2.  java代碼;

package com.chenye.dictionary;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Scanner;

public class MainActivity extends AppCompatActivity {
    private HashMap<String, String> dictionary;
    EditText wordEditText;
    TextView resultTextView;

    public  void readAllDefinition() {
        Scanner scanner = new Scanner(getResources().openRawResource(R.raw.gre_words));
        if(this.dictionary == null){
            this.dictionary = new HashMap<>();
        }
        while (scanner.hasNext()){
            String line = scanner.nextLine();
            String[] pieces = line.split("\t");
            this.dictionary.put(pieces[0], pieces[1]);

        }
        scanner.close();
    }
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        readAllDefinition();
        wordEditText = findViewById(R.id.wordEditText);
        resultTextView = findViewById(R.id.result);
        wordEditText.addTextChangedListener(new TextWatcher() {
            private CharSequence word;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
                word = charSequence;

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                //resultTextView.setText("");
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(word.length()==0) {
                    resultTextView.setText("word definition result");
                }
                else if (word.length() == 20){
                    Toast.makeText(MainActivity.this, "已到達輸入的最大長度!", Toast.LENGTH_SHORT).show();
                }
            }
        });

    }
// button的方法
    public void lookup(View view) {
        EditText wordText = findViewById(R.id.wordEditText);
        String word = wordText.getText().toString();
        if(this.dictionary == null){
            readAllDefinition();
        }
        String def = this.dictionary.get(word);
        TextView defTextView = findViewById(R.id.result);
        if(def == null){
            defTextView.setText("word not fond!");
        }else{
            defTextView.setText(def);
        }
    }
    
}
readAllDefinition()是在app啟動的時候就會被調用的方法,此時已經將所有的單詞,以及其對應的含義放在了map中;
其中,getResources().openRawResource(R.raw.gre_words)方法獲取到InputStream流, gre_words是存放單詞及對應含義的文本文件;
onCreate()方法中,分別采用wordEditText = findViewById(R.id.wordEditText);resultTextView = findViewById(R.id.result)方法獲取id
最重要的是addTextChangedListener這個方法,是監聽EditText的方法,里面有三個方法:
beforeTextChange()是在EditText改變之前里面可以做一些操作;
onTextChanged()是改變中;

afterTextChanged()是改變后;
參數:charSequence是這串字符串;start表示開始變化的位置,count表示變化的字符串長度,after表示變化之后該位置的字符數量, before表示變化之前該位置的字符數量;
3. 結果如下:
初始情況: 查詢單詞如下: 刪除單詞中間結果如下:

長度超出情況如下:

 

 

 ps: 本寶也是剛開始學習android, 記錄一下自己的學習過程,好記性不如爛筆頭!




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM