您好,登錄后才能下訂單哦!
要自定義EditText控件的撤銷操作,可以使用SpannableStringBuilder和TextWatcher來實現。以下是一個示例代碼:
public class CustomEditText extends AppCompatEditText {
private Stack<CharSequence> mUndoStack = new Stack<>();
private Stack<CharSequence> mRedoStack = 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) {
// do nothing
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mUndoStack.push(new SpannableStringBuilder(s));
mRedoStack.clear();
}
@Override
public void afterTextChanged(Editable s) {
// do nothing
}
});
}
public void undo() {
if (!mUndoStack.isEmpty()) {
CharSequence currentText = getText();
mRedoStack.push(new SpannableStringBuilder(currentText));
Editable editable = getText();
editable.clear();
editable.append(mUndoStack.pop());
}
}
public void redo() {
if (!mRedoStack.isEmpty()) {
CharSequence currentText = getText();
mUndoStack.push(new SpannableStringBuilder(currentText));
Editable editable = getText();
editable.clear();
editable.append(mRedoStack.pop());
}
}
}
在這個自定義EditText控件中,我們使用兩個棧來保存撤銷和重做的操作。在TextWatcher中,每當文字發生改變時,我們將當前的文字內容保存到撤銷棧中。通過調用undo()和redo()方法,可以實現撤銷和重做操作。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。