溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

EditText控件的文本輸入與自定義撤銷/重做

發(fā)布時(shí)間:2024-08-31 14:01:52 來源:億速云 閱讀:83 作者:小樊 欄目:移動開發(fā)

在Android中,EditText控件默認(rèn)支持文本輸入

  1. 創(chuàng)建一個(gè)自定義EditText類,繼承自AppCompatEditText。
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());
        }
    }
}
  1. 在布局文件中使用自定義EditText。
<your.package.name.CustomEditText
    android:id="@+id/custom_edit_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
  1. 在Activity或Fragment中處理撤銷和重做操作。
CustomEditText customEditText = findViewById(R.id.custom_edit_text);

// 撤銷
customEditText.undo();

// 重做
customEditText.redo();

現(xiàn)在你可以在自定義EditText中輸入文本,并通過調(diào)用undo()redo()方法實(shí)現(xiàn)撤銷和重做功能。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI