实现输入框内容在文本显示框的实时刷新显示

    xiaoxiao2021-08-22  97

    实现原理:

    使用Handler的post方法,和Runnable开启一个线程,然后使用addTextChangedListener监听EditText的内容变化,在内容变化之后调用异步线程进行刷新,让其显示到指定的TextView上。

    代码:

    import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { TextView showContent; EditText editContent; Handler mHandler; Runnable updateTextRunnable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); showContent = (TextView) findViewById(R.id.textview); editContent = (EditText) findViewById(R.id.editText); mHandler = new Handler(); updateTextRunnable = new Runnable() { @Override public void run() { showContent.setText(editContent.getText()); // 如果不想设置监听也可让其不断地运行,保证内容的刷新,不过很浪费性能; // mHandler.post(this); } }; // 监听EditeText的内容变化 editContent.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void afterTextChanged(Editable arg0) { mHandler.post(updateTextRunnable); } }); } }布局文件代码:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" android:gravity="center" android:layout_alignParentTop="true" android:id="@+id/textview"/> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:hint="input content" android:layout_centerInParent="true" > </EditText> </RelativeLayout>

    转载请注明原文地址: https://ju.6miu.com/read-676897.html

    最新回复(0)