【发布时间】:2011-07-06 14:58:53
【问题描述】:
我有一个正在处理的图像,我有两个按钮,撤消和重做。如果单击这两个按钮中的任何一个,我需要代码来撤消/重做先前的触摸操作。我知道我必须使用堆栈。我应该如何实现它?
【问题讨论】:
-
定义处理?你在用这些图片做什么?
我有一个正在处理的图像,我有两个按钮,撤消和重做。如果单击这两个按钮中的任何一个,我需要代码来撤消/重做先前的触摸操作。我知道我必须使用堆栈。我应该如何实现它?
【问题讨论】:
这一切都取决于您的触摸事件首先做什么。您必须将应用程序响应触摸所做的操作抽象到可以填充堆栈的类中。那么栈的实现就简单了。
如果是图像处理,它可能会占用太多内存来保存整个位图堆栈。在将两个或三个项目压入堆栈后,您可能会得到臭名昭著的 OutOfMemoryException。您最好做的是抽象应用程序中可用的操作并在撤消/重做时重建。您基本上是在创建一堆指令集。这使得堆栈越大速度越慢,但如果内存中的图像很大,这可能是唯一的方法。
【讨论】:
实现撤消/重做有两种主要模式:
备忘录模式的想法是,您可以保存对象的整个内部状态的副本(不违反封装)以供以后恢复。
它会被这样使用(例如):
// 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.
【讨论】:
在较新的 Android 版本 (22+) 中,您可以使用 Snackbar。这是监听器的小代码片段:
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();
【讨论】: