B4J Library [B4X] [class] UndoManager

test.gif


The UndoManager class implements a simple undo / redo system.
It is compatible with B4J, B4A and B4i.

It maintains an internal stack of states. You can use any custom type you like to represent each state as long as it is supported by B4XSerializator.

Using this class is simple. You just need to call AddState whenever there is a new state. UndoManager will compare it to the current top state and will discard duplicate states. This allows us to use a timer to add the states:
B4X:
Type UndoData (Text As String, clr As Int)

Sub Timer1_Tick
   manager.AddState(GetState) 'nothing will happen if the state is the same as the previous one
End Sub

Sub GetState As UndoData
   Dim ud As UndoData
   ud.Initialize
   ud.Text = TextArea1.Text
   ud.clr = fx.Colors.To32Bit(ColorPicker1.SelectedColor)
   Return ud
End Sub

In the above code we track the text and selected color.

All that is left to do is to call undo or redo and set back the states:
B4X:
Sub btnUndo_Action
   Dim ud As UndoData = manager.Undo
   SetState(ud)
End Sub

Sub SetState (ud As UndoData)
   TextArea1.Text = ud.Text
   ColorPicker1.SelectedColor = fx.Colors.From32Bit(ud.clr)
End Sub

The class module is in the attached example. Note that the example requires B4J v4.70+ (https://www.b4x.com/android/forum/threads/72913/#content).
If you are using it with B4i then you need to use iRandomAccessFile v1.51+.
 

Attachments

  • UndoManager.zip
    3.3 KB · Views: 772
Top