How to apply undo and redo operation to EditText on button click in android
I am trying to apply an undo and redo operation while writing or applying an effect to my EditText. To do this, I loaded the class from this Link and then I used it like this in my application.
Cancel
TextViewUndoRedo mTextViewUndoRedo = new TextViewUndoRedo(edtNoteDescription);
mTextViewUndoRedo.undo();
For reuse
TextViewUndoRedo mTextViewUndoRedo = new TextViewUndoRedo(edtNoteDescription);
mTextViewUndoRedo.redo();
But I don't know why this code is not working, I put a log and checked if the Undo function was called or not, and unfortunately I saw that it calls this function, but it goes inside the method below.
if (edit == null) {
return;
}
I also tried with some other solution with no luck. Therefore, if anyone who has implemented the same with this method or any other method, please 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();
}
});
source to share
Could the problem be that you are creating an object TextViewUndoRedo
on every button click?
This is why it is EditHistory
empty, because it is recreated every time. Wouldn't this work?
TextViewUndoRedo mTextViewUndoRedo = new TextViewUndoRedo(edtNoteDescription);
btnUndo.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTextViewUndoRedo.undo();
}
});
As I said in the comments, the method Undo()
calls mEditHistory.getPrevious()
, but getPrevious()
returns null
, because inside it, it does:
if (mmPosition == 0) {
return null;
}
On creation TextViewUndoRedo
, a new one is created EditHistory
and inside it is mmPosition
initialized to 0. Since you recreate the object every time, it is mmPosition
always 0 and you get null
back.
source to share