EditText控件的文本输入与自定义撤销/重做

发布时间:2024-08-31 14:01:52 作者:小樊
来源:亿速云 阅读:82

在Android中,EditText控件默认支持文本输入

  1. 创建一个自定义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();

现在你可以在自定义EditText中输入文本,并通过调用undo()redo()方法实现撤销和重做功能。

推荐阅读:
  1. Android中如何实现EditText随输入法一起移动并悬浮在输入法之上
  2. kotlin中EditText赋值Type mismatch方式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

edittext

上一篇:Button控件的文本自定义属性

下一篇:EditText控件的文本输入与自定义键盘快捷键

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》