3

我有一个正在处理的图像,我有两个按钮,撤消和重做。如果单击这两个按钮中的任何一个,我需要代码来撤消/重做先前的触摸操作。我知道我必须使用堆栈。我应该如何实施?

4

3 回答 3

8

实现撤消/重做有两种主要模式:

  1. “纪念品”模式。
  2. “命令”模式。

1.纪念品模式

memento 模式的想法是,您可以保存对象的整个内部状态的副本(不违反封装),以便以后恢复。

它会像这样使用(例如):

// 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);

2.命令模式

命令模式的思想是封装在对象上实际执行的操作。每个“动作”(或“命令”)都可以选择知道如何回滚。或者,当需要进行回滚时,可以再次执行整个命令链。

它会像这样使用(例如):

// 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.
于 2011-03-02T14:33:12.030 回答
4

这一切都取决于你的触摸事件首先做了什么。您必须将应用程序响应触摸所做的操作抽象为可以填充堆栈的类。然后,堆栈实现很容易。

如果是图像处理,可能会占用太多内存来保存整个位图堆栈。在将两个或三个项目压入堆栈后,您可能会得到臭名昭著的 OutOfMemoryException。您可能最好做的是抽象应用程序中可用的操作并在撤消/重做时重建。您基本上是在创建一堆指令集。这使得堆栈越大越慢,但如果内存中的图像很大,它可能是唯一的方法。

于 2011-03-01T16:03:51.177 回答
0

在较新的 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();
于 2017-04-03T16:10:27.673 回答