按钮控制EditText删除单个字符

来源:互联网 发布:python ggplot风格 编辑:程序博客网 时间:2024/06/11 02:37

情景描述
有时,我们在开发Android中遇到模拟软键盘的删除键一样的功能,即通过“删除”按钮去删除EditText单个字符。

方法就一句话:
editText.dispatchKeyEvent(new KeyEvent(
KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
就能达到跟软键盘删除键一样的删除效果。

代码区:
Xml中

<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="testwebricheditor.demo.com.richeditor.MainActivity">    <EditText        android:id="@+id/et"        android:layout_width="match_parent"        android:layout_height="wrap_content"        app:layout_constraintBottom_toBottomOf="parent"        app:layout_constraintLeft_toLeftOf="parent"        app:layout_constraintRight_toRightOf="parent"        app:layout_constraintTop_toTopOf="parent" />    <Button        android:id="@+id/delete"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="delete"        android:textColor="#ff00ff"        android:textSize="18sp" /></android.support.constraint.ConstraintLayout>

activity中

package testwebricheditor.demo.com.richeditor;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.KeyEvent;import android.view.View;import android.widget.Button;import android.widget.EditText;public class MainActivity extends AppCompatActivity {    EditText editText;    Button delete;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        editText = findViewById(R.id.et);        delete = findViewById(R.id.delete);        delete.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                editText.dispatchKeyEvent(new KeyEvent(                        KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));            }        });    }}

如果有问题的话 请检查自定义控件写法或者逻辑问题。

原创粉丝点击