我有一张正在处理的图片,还有两个按钮,撤销和重做。如果点击其中任何一个按钮,我需要撤销/重做先前的触摸操作。我知道我必须使用堆栈。应该如何实现?
实现撤销/重做的主要模式有两种:
备忘录模式的思想是可以保存对象的整个内部状态(不违反封装)以便以后恢复。
它会像这样使用(例如):
// Create your object that can be "undone"
ImageObject myImage = new ImageObject()
// Save an "undo" point.
var memento = myImage.CreateMemento();
// do a bunch of crazy stuff to the image...
// ...
// Restore to a previous state.
myImage.SetMemento(memento);
命令模式的思想是封装在对象上实际执行的操作。每个“动作”(或“命令”)可以选择知道如何回滚自己。或者,当需要进行回滚时,可以再次执行整个命令链。
例如,它可以像这样使用:
// Create your object that can be "undone"
ImageObject myImage = new ImageObject()
// Create a "select all" command
var command = new SelectAllCommand(myImage); // This does not actually execute the action.
// Apply the "select all" command to the image
selectAll.Execute(); // In this example, the selectAll command would "take note" of the selection that it is overwriting.
// When needed, rollback:
selectAll.Rollback(); // This would have the effect of restoring the previous selection.
一切都取决于您的触摸事件首先执行什么操作。 您必须将应用程序响应触摸的内容抽象成一个类,然后使用该类填充一个堆栈。 然后,堆栈实现就很容易。
如果涉及图像处理,保留整个位图堆栈可能会占用太多内存。 将您应用程序中可用的操作进行抽象化,然后在撤销/重做时重新构建。 您基本上正在创建指令集的堆栈。 随着堆栈越来越大,这会使其变慢,但如果内存中的图像很大,这可能是唯一的方法。
public class MyUndoListener implements View.OnClickListener{
&Override
public void onClick(View v) {
// Code to undo the user's last action
}
}
同时,在屏幕底部创建一条消息以执行“撤销”操作:
Snackbar mySnackbar = Snackbar.make(findViewById(R.id.myCoordinatorLayout),
R.string.email_archived, Snackbar.LENGTH_SHORT);
mySnackbar.setAction(R.string.undo_string, new MyUndoListener());
mySnackbar.show();