在Android中,EditText控件默认支持文本输入
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatEditText;
import java.util.Stack;
public class CustomEditText extends AppCompatEditText {
private Stack<String> undoStack = new Stack<>();
private Stack<String> redoStack = new Stack<>();
public CustomEditText(Context context) {
super(context);
init();
}
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (undoStack.isEmpty() || !undoStack.peek().equals(s.toString())) {
undoStack.push(s.toString());
redoStack.clear();
}
}
});
}
public void undo() {
if (!undoStack.isEmpty()) {
String text = undoStack.pop();
redoStack.push(getText().toString());
setText(text);
setSelection(text.length());
}
}
public void redo() {
if (!redoStack.isEmpty()) {
String text = redoStack.pop();
undoStack.push(getText().toString());
setText(text);
setSelection(text.length());
}
}
}
<your.package.name.CustomEditText
android:id="@+id/custom_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
CustomEditText customEditText = findViewById(R.id.custom_edit_text);
// 撤销
customEditText.undo();
// 重做
customEditText.redo();
现在你可以在自定义EditText中输入文本,并通过调用undo()
和redo()
方法实现撤销和重做功能。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。