您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。