按鈕控制EditText刪除單個字元
阿新 • • 發佈:2019-01-06
情景描述
有時,我們在開發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));
}
});
}
}
如果有問題的話 請檢查自定義控制元件寫法或者邏輯問題。