How to apply Undo and Redo operation to EditText o

2019-07-07 03:18发布

问题:

I am trying to apply Undo and Redo operation while writing or applying effect to my EditText. For that i have downloaded class from this Link and then i have used it like this in my app.

For Undo

TextViewUndoRedo mTextViewUndoRedo = new TextViewUndoRedo(edtNoteDescription);
mTextViewUndoRedo.undo();

For Redo

TextViewUndoRedo mTextViewUndoRedo = new TextViewUndoRedo(edtNoteDescription);
mTextViewUndoRedo.redo();

But i don't know why this code does not work, I have put the log and check whether the function Undo is called or not and unfortunately i saw that it is calling this function but it goes inside below method.

if (edit == null) {
    return;
}

I have also tried with some other solution with no luck, So if anyone who has implemented the same with this method or with any other method then please do suggest some code or way to implement this functionality.

Edit

btnUndo.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                 TextViewUndoRedo mTextViewUndoRedo = new TextViewUndoRedo(edtNoteDescription);
                 mTextViewUndoRedo.undo();
            }
        });

回答1:

Could the problem be that you are creating the TextViewUndoRedo object each time the button is clicked?

That is why EditHistory is empty cause it's getting recreated each time. Wouldn't this work?

TextViewUndoRedo mTextViewUndoRedo = new TextViewUndoRedo(edtNoteDescription);

btnUndo.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        mTextViewUndoRedo.undo();
    }
});

Like I said in the comments, The Undo() method calls mEditHistory.getPrevious() but getPrevious() returns null because inside of it, it executes:

if (mmPosition == 0) { 
    return null; 
} 

When TextViewUndoRedo is created, a new EditHistory is created and inside of it mmPosition is initialized to 0. Since you are re-creating the object each time, mmPosition is always 0 and you get null back.