今天看了备忘录模式,顺便按着书上的案例敲了一篇,书本上有个地方需要改良的就是每次它只会remove(0),并没有实现动态删除,下面附上整个小demo的全部代码,实现一个简单的备忘录:
创建存储类Bean类
- 该类作用是存在保存的内容和光标所在位置
代码如下:public class Memoto {public String text;public int cursor;//光标所在位置public String getText() {return text;}public void setText(String text) {this.text = text;}public int getCursor() {return cursor;}public void setCursor(int cursor) {this.cursor = cursor;}}
创建管理备忘录的类
- 该类负责存储Memoto数据,防止外部直接访问Memoto
代码如下:public class NoteCaretaker {private static final int MAX = 30;private List<Memoto> mMemotos = new ArrayList<Memoto>(MAX);private int index = 0;public void saveMemoto(Memoto memoto){index = mMemotos.size() - 1;if(mMemotos.size() > MAX){// mMemotos.remove(0);(作者的源码)mMemotos.remove(index - MAX);//改良(有序删除,假如31进来就删除0,32进来就删除1)}mMemotos.add(memoto);}public Memoto getPrevMemeto(){index = index > 0? --index:index;return mMemotos.get(index);}public Memoto getNextMemeto(){index = index < mMemotos.size() - 1?++index:index;return mMemotos.get(index);}}
替作者改良位置:
mMemotos.remove(index - MAX);
改良说明:这是进行动态有序删除,假如31进来就删除0,32进来就删除1.这样就不会仅仅局限于30个点,而是动态相连接的30个保存点。
自定义EditText
- 自定义EditText减少Activity中代码重复使用
代码如下:public class NoteEditText extends EditText {public NoteEditText(Context context) {super(context);}public NoteEditText(Context context, AttributeSet attrs) {super(context, attrs);}public NoteEditText(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}//创建备忘录对象,即存储编辑器的指定数据public Memoto createMemoto(){Memoto noteMemoto = new Memoto();noteMemoto.setText(getText().toString());noteMemoto.setCursor(getSelectionStart());return noteMemoto;}//从备忘录中恢复数据public void restore(Memoto memoto){setText(memoto.getText());setSelection(memoto.getCursor());}}
测试功能代码
代码如下:
|
效果图
初始效果图
保存效果图
为撤销功能做准备保存第二次: