实现效果:

实现的功能:

查看记事列表:登录成功后,系统进入第二个活动,系统查询数据库里面所有的记事项,如记事标题/内容/时间,将查询到的信息存放在ListView里,形成记事列表,记事列表可以点击相应的条目,监听器监听点击事件,点击后跳转到记事编辑页面。
记事列表增加长按事件监听,当长按列表条目后,弹出弹窗,弹窗提示“确认删除”,有确认和取消两个按钮,点击确认按钮后,获取到对应列表的id信息,根据id信息删除数据库中的相应内容。
点击右侧的“X”按钮,弹出弹窗,弹窗提示“确认删除全部记事内容”,有确认和取消两个按钮,点击确认按钮后清空记事本的Note表,删除所有的记事内容。
添加搜索框输入文字的事件监听,当在搜索框中输入内容时,获取输入内容并根据输入内容对记事本的数据表title内容进行模糊检索,查找出记事项中包含关键词的数据项,记事列表会根据输入的内容实时显示检索的结果。
点击右侧的上/下箭头会对记事进行降序/升序排序,触发对数据库数据的降序排序,然后根据排完旭的数据对例表项进行对降序/升序排序。
在记事列表页点击右侧“+”按钮,跳转到记事项编辑页面。

xml代码

activity_item_detail.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/activity_main"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><include layout="@layout/search_item">android:layout_alignParentTop ="true"</include><!--显示头像,记得加入id iv_head --><android.support.v4.widget.SwipeRefreshLayoutandroid:layout_below ="@+id/title_bar"android:id="@+id/swipe_refresh"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginTop="20dp"><LinearLayoutandroid:layout_height="wrap_content"android:layout_width="match_parent"android:orientation="vertical"><ListViewandroid:id="@+id/note_list"android:layout_width="match_parent"android:layout_height="wrap_content"></ListView><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:gravity="center"android:layout_gravity="center"android:text="@string/btn_refresh"/></LinearLayout></android.support.v4.widget.SwipeRefreshLayout><Buttonandroid:id="@+id/btn_add"android:gravity="center"android:layout_width="40dp"android:layout_height="40dp"android:background="@drawable/add"android:layout_marginBottom="30dp"android:layout_marginRight="40dp"android:layout_alignParentBottom="true"android:layout_alignParentEnd="true" /><Buttonandroid:id="@+id/btn_delete"android:gravity="center"android:layout_width="42dp"android:layout_height="42dp"android:background="@drawable/del"android:layout_marginBottom="90dp"android:layout_marginRight="38dp"android:layout_alignParentBottom="true"android:layout_alignParentEnd="true" /><Buttonandroid:id="@+id/btn_up"android:gravity="center"android:layout_width="30dp"android:layout_height="30dp"android:layout_alignParentBottom="true"android:layout_marginBottom="185dp"android:background="@drawable/up"android:layout_marginRight="6dp"android:layout_alignEnd="@+id/btn_delete"android:layout_above="@+id/btn_down" /><Buttonandroid:id="@+id/btn_down"android:gravity="center"android:layout_width="30dp"android:layout_height="30dp"android:background="@drawable/down"android:layout_alignParentBottom="true"android:layout_marginBottom="160dp"android:layout_marginRight="0dp"android:layout_centerVertical="true"android:layout_alignStart="@+id/btn_up" /></RelativeLayout>

列表项的具体布局
item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_marginTop="10dp"
android:padding="5dp"
android:orientation="horizontal">
<ImageViewandroid:id="@+id/rand_icon"android:layout_width="40dp"android:layout_height="40dp"android:background="@drawable/book"android:padding="2dp"android:layout_margin="4dp" />
<LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:weightSum="1"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_marginLeft="8dp"android:layout_weight="0.6"android:weightSum="1"android:orientation="horizontal"><TextViewandroid:id="@+id/item_note_title"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="0.5"android:textSize="20dp"android:textColor="@color/colorPrimary"android:gravity="center_vertical"android:singleLine="true"/><TextViewandroid:id="@+id/item_note_date"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="0.5"android:textSize="14dp"android:layout_gravity="right"android:gravity="center_vertical"android:singleLine="true"/></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="0dp"android:layout_marginLeft="8dp"android:layout_weight="0.4"android:weightSum="1"android:orientation="horizontal"><TextViewandroid:id="@+id/des"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="0.50"android:textSize="14dp"android:textColor="@color/colorPrimary"android:gravity="center_vertical"android:singleLine="true"/><TextViewandroid:id="@+id/pre"android:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="0.5"android:textSize="14dp"android:textColor="@color/colorPrimary"android:layout_gravity="right"android:gravity="center_vertical"android:singleLine="true"/></LinearLayout>
</LinearLayout></LinearLayout>

搜索框的页面布局
search_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/title_bar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#84a9ac"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="50dp"android:gravity="center"android:orientation="horizontal"android:weightSum="1"><EditTextandroid:id="@+id/edit_search"android:layout_width="wrap_content"android:layout_height="38dp"android:background="#ffffff"android:gravity="center_vertical"android:hint=" 请输入关键词查询!"android:layout_gravity="center"android:imeOptions="actionSearch"android:layout_margin="2dp"android:singleLine="true"android:layout_weight="0.67" /><Buttonandroid:id="@+id/btn_search"android:gravity="center"android:layout_width="30dp"android:layout_height="30dp"android:layout_marginLeft="14dp"android:background="@drawable/serch" /></LinearLayout>
</LinearLayout>

java代码
NoteDateBaseHelper.java——数据库

package com.example.lsl.daily_note;import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;/*** Created by lsl on 2020/6/9.*///创建数据库public class NoteDataBaseHelper extends SQLiteOpenHelper {public NoteDataBaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {super(context, name, factory, version);}//表创建接口 有多张表时 方便统一调用public static interface TableCreateInterface {//创建表public void onCreate(SQLiteDatabase db);//更新表public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);}@Overridepublic void onCreate(SQLiteDatabase db) {//具体表的创建Note.getInstance().onCreate(db);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//具体表的更新Note.getInstance().onUpgrade(db, oldVersion, newVersion);}
}

Note.java——对数据的具体操作

package com.example.lsl.daily_note;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.widget.Toast;import java.util.HashMap;/*** Created by lsl on 2020/6/10.*///用于管理数据库的类public class Note implements NoteDataBaseHelper.TableCreateInterface {// 定义表名public static String tableName = "Note";// 定义各字段名public static String _id = "_id"; // _id是SQLite中自动生成的主键,用语标识唯一的记录,为了方便使用,此处定义对应字段名public static String title = "title"; // 标题public static String content = "content"; // 内容public static String time = "date"; // 时间public static String pre = "pre";//设置的优先级public static String picture = "picture";//图片//私有化构造方法private Note() {}//初始化实例private static Note note = new Note();//只提供一个实例public static Note getInstance() {return note;}//实现表的创建@Overridepublic void onCreate(SQLiteDatabase db) {String sql = "CREATE TABLE "+ Note.tableName+ " (  "+ "_id integer primary key autoincrement, "
//                + Note.id + "TEXT,"+ Note.title + " TEXT, "+ Note.content + " TEXT, "+ Note.time + " TEXT, "+ Note.pre + " TEXT, "+ Note.picture + " BLOB "+ ");";db.execSQL(sql);}//实现表的更新@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {if (oldVersion < newVersion) {String sql = "DROP TABLE IF EXISTS " + Note.tableName;db.execSQL(sql);this.onCreate(db);}}// 插入public static void insertNote(NoteDataBaseHelper dbHelper, ContentValues userValues) {SQLiteDatabase db = dbHelper.getWritableDatabase();db.insert(Note.tableName, null, userValues);db.close();}// 删除一条笔记public static void deleteNote(NoteDataBaseHelper dbHelper, int _id) {SQLiteDatabase db = dbHelper.getWritableDatabase();db.delete(Note.tableName, Note._id + "=?", new String[]{_id + ""});
//        Cursor cursor = db.query(Note.tableName, null, null, null, null, null, null);
//        return cursor;db.close();}// 删除所有笔记public static void deleteAllNote(NoteDataBaseHelper dbHelper) {SQLiteDatabase db = dbHelper.getWritableDatabase();db.delete(Note.tableName, null, null);db.close();}// 修改public static void updateNote( NoteDataBaseHelper dbHelper,  int _id, ContentValues infoValues ) {SQLiteDatabase db = dbHelper.getWritableDatabase();db.update(Note.tableName, infoValues, Note._id + " =? ", new String[]{ _id + "" });db.close();}//搜索c查询数据// 以HashMap<String, Object>键值对的形式获取一条信息public static HashMap<String, Object> getNote(NoteDataBaseHelper dbHelper, int _id) {SQLiteDatabase db = dbHelper.getReadableDatabase();HashMap<String, Object> NoteMap = new HashMap<String, Object>();// 此处要求查询Note._id为传入参数_id的对应记录,使游标指向此记录Cursor cursor = db.query(Note.tableName, null, Note._id + " =? ", new String[]{_id + ""}, null, null, null);cursor.moveToFirst();NoteMap.put(Note.title, cursor.getLong(cursor.getColumnIndex(Note.title)));NoteMap.put(Note.content, cursor.getString(cursor.getColumnIndex(Note.content)));NoteMap.put(Note.time, cursor.getString(cursor.getColumnIndex(Note.time)));NoteMap.put(Note.pre, cursor.getString(cursor.getColumnIndex(Note.pre)));NoteMap.put(Note.picture, cursor.getBlob(cursor.getColumnIndex(Note.picture)));return NoteMap;}// 获得查询指向Note表的游标public static Cursor getAllNotes(NoteDataBaseHelper dbHelper) {SQLiteDatabase db = dbHelper.getReadableDatabase();Cursor cursor = db.query(Note.tableName, null, null, null, null, null, null);cursor.moveToFirst();return cursor;}public static Cursor getSearchNotes(NoteDataBaseHelper dbHelper,String searcher) {SQLiteDatabase db = dbHelper.getReadableDatabase();Cursor cursor = db.rawQuery("select * from Note where title like '%"+searcher+"%'",null);cursor.moveToFirst();return cursor;}public static Cursor upNotes(NoteDataBaseHelper dbHelper) {SQLiteDatabase db = dbHelper.getReadableDatabase();Cursor cursor = db.rawQuery("SELECT * FROM Note order by cast(pre as '9999')",null);cursor.moveToFirst();return cursor;}public static Cursor downNotes(NoteDataBaseHelper dbHelper) {SQLiteDatabase db = dbHelper.getReadableDatabase();Cursor cursor = db.rawQuery("SELECT * FROM Note order by cast(pre as '9999') desc",null);cursor.moveToFirst();return cursor;}
}

NoteInfo.java

package com.example.lsl.daily_note;import android.graphics.Bitmap;import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** Created by lsl on 2020/6/10.*/public class NoteInfo implements Serializable {private String id;private String title;private String content;private String date;private String des;private String pre;private byte[] photo;//getter and setterpublic String getTitle() {return title;}public String getDate() {return date;}public String getId() {return id;}public String getPre(){return pre;}public void setPre(String pre) {this.pre = pre;}public String getDes(){//定义正则表达式,用于匹配路径String content = getContent();Pattern p=Pattern.compile("/([^\\.]*)\\.\\w{3}");Matcher m=p.matcher(content);StringBuffer strBuff = new StringBuffer();String title = "";int startIndex = 0;while(m.find()){//取出路径前的文字if(m.start() > 0){strBuff.append(content.substring(startIndex, m.start()));}//取出路径String path = m.group().toString();//取出路径的后缀String type = path.substring(path.length() - 3, path.length());//判断附件的类型if(type.equals("amr")){strBuff.append("[录音]");}else{strBuff.append("[图片]");}startIndex = m.end();//只取出前15个字作为标题if(strBuff.length() > 15){//统一将回车,等特殊字符换成空格title = strBuff.toString().replaceAll("\r|\n|\t", " ");return title;}}strBuff.append(content.substring(startIndex, content.length()));//统一将回车,等特殊字符换成空格title = strBuff.toString().replaceAll("\r|\n|\t", " ");return title;}public byte[] getPhoto(){return photo;}public void setPhoto(byte[] photo){this.photo = photo;}public void setId(String id) {this.id = id;}public void setTitle(String title) {this.title = title;}public void setContent(String content) {this.content = content;}public void setDes(String des) {this.des = getDes();}public void setDate(String date) {this.date = date;}public String getContent() {return content;}
}

ListAdapter.java

package com.example.lsl.daily_note;import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;/*** Created by lsl on 2020/6/10.*///适配器 用于配置列表的item
class ViewHolder{public ImageView itemIcon;public TextView itemNoteTitle;public TextView itemNoteDate;public TextView itemNoteDes;public TextView itemNotePer;View itemView;public ViewHolder(View itemView) {if (itemView == null){throw new IllegalArgumentException("item View can not be null!");}this.itemView = itemView;itemIcon = (ImageView) itemView.findViewById(R.id.rand_icon);itemNoteTitle = (TextView) itemView.findViewById(R.id.item_note_title);itemNoteDate = (TextView) itemView.findViewById(R.id.item_note_date);itemNoteDes = (TextView) itemView.findViewById(R.id.des);itemNotePer = (TextView) itemView.findViewById(R.id.pre);}
}
public class ListAdapter extends BaseAdapter {private List<NoteInfo> noteList;private LayoutInflater layoutInflater;private Context context;private ViewHolder holder = null;public ListAdapter(Context context,List<NoteInfo> noteList) {this.noteList = noteList;this.context = context;layoutInflater = LayoutInflater.from(context);}@Overridepublic int getCount() {return noteList.size();}@Overridepublic Object getItem(int position) {return noteList.get(position).getTitle();}@Overridepublic long getItemId(int position) {return Long.parseLong(noteList.get(position).getId());}public void remove(int index){noteList.remove(index);}public void refreshDataSet(){notifyDataSetChanged();}@Overridepublic View getView(int position, View convertView, ViewGroup parent) {if (convertView == null){convertView = layoutInflater.inflate(R.layout.item_layout,null);holder = new ViewHolder(convertView);convertView.setTag(holder);}else {holder = (ViewHolder)convertView.getTag();}holder.itemNoteTitle.setText(noteList.get(position).getTitle());holder.itemNoteDate.setText(noteList.get(position).getDate());holder.itemNoteDes.setText(noteList.get(position).getDes());holder.itemNotePer.setText("记事项优先级:"+noteList.get(position).getPre());return convertView;}
}

NoteEditorActivity.java

package com.example.lsl.daily_note;import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.ContentValues;
import android.widget.EditText;
import android.widget.Toast;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.Button;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;import static com.example.lsl.daily_note.Note.content;
import static com.example.lsl.daily_note.Note.updateNote;/*** Created by lsl on 2020/6/8.*/public class NoteEditorActivity extends AppCompatActivity {private TextView tv_main_title;//标题private TextView tv_now;//现在的时间private EditText et_title;//标题private EditText et_content;//内容private EditText et_pre;//设置优先级private Button btn_save;//保存private Button btn_return;//取消private ImageView pic_button;//插入图片按钮public Drawable photodrawable;//插入的图片(有默认的图片)private ImageView testpic;public static final int TAKE_PHOTO = 1;public static final int CHOOSE_PHOTO = 2;public Bitmap photobitmap ;//图片的Bitmap格式public byte[] photobyte = new byte[1024];//图片转为byte类型存入数据库(有默认图片)private NoteInfo currentNote;public byte[] showbyte = new byte[1024];public Bitmap showbitmap;//记录是否是插入状态 (因为也可能是更新(编辑)状态)private boolean insertFlag = true;/*** ATTENTION: This was auto-generated to implement the App Indexing API.* See https://g.co/AppIndexing/AndroidStudio for more information.*/private GoogleApiClient client;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.note_editor);//设置此界面为竖屏setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置添加事项页面图标大小// 设置标题图标大小TextView editTitle = (TextView) findViewById(R.id.et_title);Drawable title1 = getResources().getDrawable(R.drawable.title);title1.setBounds(0, 0, 50, 50);//第一0是距左边距离,第二0是距上边距离,40分别是长宽editTitle.setCompoundDrawables(title1, null, null, null);//只放左边tv_main_title = (TextView) findViewById(R.id.tv_main_title);initView();setListener();Intent intent = getIntent();Bundle bundle = intent.getExtras();//主界面点击ListView中的一个Item跳转时if (bundle != null) {currentNote = (NoteInfo) bundle.getSerializable("noteInfo");et_title.setText(currentNote.getTitle());tv_now.setText(currentNote.getDate());et_content.setText(currentNote.getContent());et_pre.setText(currentNote.getPre());showbyte = currentNote.getPhoto();
            //把byte格式的图片转为bitmap格式的图片showbitmap = BitmapFactory.decodeByteArray(showbyte, 0, showbyte.length);pic_button.setImageBitmap(showbitmap);}// ATTENTION: This was auto-generated to implement the App Indexing API.// See https://g.co/AppIndexing/AndroidStudio for more information.client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();//解决android7调用照相机后直接闪退问题if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();StrictMode.setVmPolicy(builder.build());}}//保存数据private void saveNote() {NoteDataBaseHelper dbHelper = ItemDetailActivity.getDbHelper();ContentValues values = new ContentValues();values.put(Note.title, et_title.getText().toString());values.put(Note.content, et_content.getText().toString());values.put(Note.pre, et_pre.getText().toString());values.put(Note.time, getTime().toString());photodrawable = pic_button.getDrawable();photobyte=dratobyte( photodrawable);values.put(Note.picture,photobyte);if (insertFlag) {Note.insertNote(dbHelper, values);} else {updateNote(dbHelper, Integer.parseInt(currentNote.getId()), values);}
}//初始化界面private void initView() {btn_save = (Button) findViewById(R.id.btn_save);btn_return = (Button) findViewById(R.id.btn_return);tv_now = (TextView) findViewById(R.id.tv_now);et_content = (EditText) findViewById(R.id.et_content);et_title = (EditText) findViewById(R.id.et_title);et_pre = (EditText) findViewById(R.id.itempre);pic_button = (ImageView) findViewById(R.id.pic);testpic = (ImageView) findViewById(R.id.testpic);photodrawable = pic_button.getDrawable();tv_now.setText(getTime());
//        //把drawable格式转为bytephotobyte = dratobyte(photodrawable);photobitmap = BitmapFactory.decodeByteArray(photobyte, 0, photobyte.length);}//时间的显示private String getTime() {SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");Date curDate = new Date();String str = format.format(curDate);return str;}//设置监听器private void setListener() {pic_button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {new AlertDialog.Builder(NoteEditorActivity.this).setIcon(R.drawable.picture).setMessage("插入图片").setPositiveButton(R.string.photograph, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {takePhoto();}}).setNegativeButton(R.string.photo_album, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {chooseFromAlbum();//  用户授权了权限申请之后就会调用该方法}}).create().show();}});btn_return.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {onBackPressed();}});btn_save.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (et_title.getText().toString().equals("") || et_content.getText().toString().equals("") || et_pre.getText().toString().equals("")) {Toast.makeText(NoteEditorActivity.this, "输入框不能为空,保存失败", Toast.LENGTH_LONG).show();Intent intent = new Intent(NoteEditorActivity.this, ItemDetailActivity.class);startActivity(intent);NoteEditorActivity.this.finish();insertFlag = false;}if (currentNote!=null&&currentNote.getDate().toString().equals(tv_now.getText().toString())){insertFlag = false;currentNote.setTitle(et_title.getText().toString());currentNote.setContent(et_content.getText().toString());currentNote.setPre(et_pre.getText().toString());currentNote.setDate(getTime().toString());currentNote.setPhoto(dratobyte(pic_button.getDrawable()));saveNote();Intent intent = new Intent(NoteEditorActivity.this, ItemDetailActivity.class);startActivity(intent);NoteEditorActivity.this.finish();Toast.makeText(NoteEditorActivity.this, R.string.save_succ, Toast.LENGTH_LONG).show();}else {saveNote();Intent intent = new Intent(NoteEditorActivity.this, ItemDetailActivity.class);startActivity(intent);NoteEditorActivity.this.finish();Toast.makeText(NoteEditorActivity.this, R.string.save_succ, Toast.LENGTH_LONG).show();}}});}@Overridepublic void onBackPressed() {if (et_title.getText().toString().equals("") || et_content.getText().toString().equals("") ||et_pre.getText().toString().equals("")) {Intent intent = new Intent(NoteEditorActivity.this, ItemDetailActivity.class);startActivity(intent);NoteEditorActivity.this.finish();Toast.makeText(NoteEditorActivity.this,"输入框不能为空,保存失败", Toast.LENGTH_LONG).show();}else {if (currentNote != null && currentNote.getDate().toString().equals(tv_now.getText().toString())&& currentNote.getTitle().toString().equals(et_title.getText().toString())&& currentNote.getContent().toString().equals(et_content.getText().toString())&& currentNote.getPre().toString().equals(et_pre.getText().toString())&& currentNote.getPhoto().toString().equals(dratobyte(pic_button.getDrawable()).toString())) {Intent intent = new Intent(NoteEditorActivity.this, ItemDetailActivity.class);startActivity(intent);NoteEditorActivity.this.finish();}else {String title = "警告";new AlertDialog.Builder(NoteEditorActivity.this).setIcon(R.drawable.book).setTitle(title).setMessage("是否保存当前内容?").setPositiveButton(R.string.btn_confirm, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {if (currentNote != null && currentNote.getDate().toString().equals(tv_now.getText().toString())) {insertFlag = false;currentNote.setTitle(et_title.getText().toString());currentNote.setContent(et_content.getText().toString());currentNote.setPre(et_pre.getText().toString());currentNote.setDate(getTime().toString());saveNote();Intent intent = new Intent(NoteEditorActivity.this, ItemDetailActivity.class);startActivity(intent);NoteEditorActivity.this.finish();Toast.makeText(NoteEditorActivity.this, R.string.save_succ, Toast.LENGTH_LONG).show();}else {saveNote();Intent intent = new Intent(NoteEditorActivity.this, ItemDetailActivity.class);startActivity(intent);NoteEditorActivity.this.finish();Toast.makeText(NoteEditorActivity.this, R.string.save_succ, Toast.LENGTH_LONG).show();}}}).setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Intent intent = new Intent(NoteEditorActivity.this, ItemDetailActivity.class);startActivity(intent);NoteEditorActivity.this.finish();}}).create().show();}}}/*** ATTENTION: This was auto-generated to implement the App Indexing API.* See https://g.co/AppIndexing/AndroidStudio for more information.*/public Action getIndexApiAction() {Thing object = new Thing.Builder().setName("NoteEditor Page") // TODO: Define a title for the content shown.// TODO: Make sure this auto-generated URL is correct..setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")).build();return new Action.Builder(Action.TYPE_VIEW).setObject(object).setActionStatus(Action.STATUS_TYPE_COMPLETED).build();}@Overridepublic void onStart() {super.onStart();// ATTENTION: This was auto-generated to implement the App Indexing API.// See https://g.co/AppIndexing/AndroidStudio for more information.client.connect();AppIndex.AppIndexApi.start(client, getIndexApiAction());}@Overridepublic void onStop() {super.onStop();// ATTENTION: This was auto-generated to implement the App Indexing API.// See https://g.co/AppIndexing/AndroidStudio for more information.AppIndex.AppIndexApi.end(client, getIndexApiAction());client.disconnect();}public void takePhoto() {Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//区分选择相片startActivityForResult(intent, 2);}public void chooseFromAlbum() {Intent intent;//添加图片的主要代码intent = new Intent();//设定类型为imageintent.setType("image/*");//设置actionintent.setAction(Intent.ACTION_GET_CONTENT);//选中相片后返回本ActivitystartActivityForResult(intent, 1);}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);if (resultCode == RESULT_OK) {//取得数据Uri uri = data.getData();ContentResolver cr = NoteEditorActivity.this.getContentResolver();Bitmap bitmap = null;Bundle extras = null;//如果是选择照片if (requestCode == 1) {try {//将对象存入Bitmap中bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//如果选择的是拍照if (requestCode == 2) {System.out.println("-----fjwefowefwef");try {if (uri != null)//这个方法是根据Uri获取Bitmap图片的静态方法bitmap = MediaStore.Images.Media.getBitmap(cr, uri);//这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片elseextras = data.getExtras();bitmap = extras.getParcelable("data");} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}int imgWidth = bitmap.getWidth();int imgHeight = bitmap.getHeight();double partion = imgWidth * 1.0 / imgHeight;double sqrtLength = Math.sqrt(partion * partion + 1);//新的缩略图大小double newImgW = 680 * (partion / sqrtLength);double newImgH = 680  * (1 / sqrtLength);float scaleW = (float) (newImgW / imgWidth);float scaleH = (float) (newImgH / imgHeight);Matrix mx = new Matrix();//对原图片进行缩放mx.postScale(scaleW, scaleH);bitmap = Bitmap.createBitmap(bitmap, 0, 0, imgWidth, imgHeight, mx, true);bitmap = getBitmapHuaSeBianKuang(bitmap);pic_button.setImageBitmap(bitmap);}}//把图片转换成字节 bitmap转变为 bytepublic  byte[] imgtobyte(Bitmap bitmap) {//        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;ByteArrayOutputStream baos = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);return baos.toByteArray();}//把图片转变为字节 drawable转变为bytepublic byte[] dratobyte(Drawable drawable){BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;Bitmap bitmap = bitmapDrawable.getBitmap();ByteArrayOutputStream baos = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);return baos.toByteArray();}//等比例缩放图片private Bitmap resize(Bitmap bitmap,int S){int imgWidth = bitmap.getWidth();int imgHeight = bitmap.getHeight();double partion = imgWidth*1.0/imgHeight;double sqrtLength = Math.sqrt(partion*partion + 1);//新的缩略图大小double newImgW = S*(partion / sqrtLength);double newImgH = S*(1 / sqrtLength);float scaleW = (float) (newImgW/imgWidth);float scaleH = (float) (newImgH/imgHeight);Matrix mx = new Matrix();//对原图片进行缩放mx.postScale(scaleW, scaleH);bitmap = Bitmap.createBitmap(bitmap, 0, 0, imgWidth, imgHeight, mx, true);return bitmap;}//给图片加边框,并返回边框后的图片public Bitmap getBitmapHuaSeBianKuang(Bitmap bitmap) {float frameSize = 0.2f;Matrix matrix = new Matrix();// 用来做底图Bitmap bitmapbg = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(), Bitmap.Config.ARGB_8888);// 设置底图为画布Canvas canvas = new Canvas(bitmapbg);canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG| Paint.FILTER_BITMAP_FLAG));float scale_x = (bitmap.getWidth() - 2 * frameSize - 2) * 1f/ (bitmap.getWidth());float scale_y = (bitmap.getHeight() - 2 * frameSize - 2) * 1f/ (bitmap.getHeight());matrix.reset();matrix.postScale(scale_x, scale_y);// 对相片大小处理(减去边框的大小)bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), matrix, true);Paint paint = new Paint();paint.setColor(Color.WHITE);paint.setStrokeWidth(1);paint.setStyle(Paint.Style.FILL);// 绘制底图边框canvas.drawRect(new Rect(0, 0, bitmapbg.getWidth(), bitmapbg.getHeight()),paint);// 绘制灰色边框paint.setColor(Color.GRAY);canvas.drawRect(new Rect((int) (frameSize), (int) (frameSize), bitmapbg.getWidth() - (int) (frameSize), bitmapbg.getHeight()- (int) (frameSize)), paint);canvas.drawBitmap(bitmap, frameSize + 2, frameSize + 2, paint);return bitmapbg;}
}

下一篇—记事本添加记事项目编辑页面

Android记事本——记事本记事列表页实现相关推荐

  1. android自定义视频列表,Android仿京东天猫列表页播视频看这一篇就足够了

    阅读本文解决什么问题? 解决android 滑动列表页自动播视频中的一些技术难点.助力更好的实现类似需求.不涉及到播放器的具体编解码技术,因为各家用的播放器可能都不一样(其实是我不会~) 何时播视频最 ...

  2. android mysql 记事本_android项目 之 记事本(11) ----- 加入数据库

    本文是自己学习所做笔记.欢迎转载.但请注明出处:http://blog.csdn.net/jesson20121020 通过之前的10节,已实现了记事本的大部分功能,有加入拍照.加入照片,加入录音,加 ...

  3. 基于android平台的云记事本软件,安卓记事本毕业论文--基于Android平台记事本的设计与实现...

    安卓记事本毕业论文--基于Android平台记事本的设计与实现 毕业设计(论文) 题目基于 Android 平台记事本的设计与实现 姓 名 学 号 系 (院) 信息工程系 班 级 指导教师 职 称 讲 ...

  4. Android简易记事本

    此次做的Android简易记事本的存储方式使用了SQLite数据库,然后界面的实现比较简单,但是,具有增删改查的基本功能,这里可以看一下效果图,如下: 具体操作就是长按可以删除操作,点击可以进行修改, ...

  5. 猿创征文|Android 11.0 12.0Launcher3中app列表页的app名称分两行显示

    1.概述 在Launcher3桌面显示列表中,由于在app列表页中,由于有些app名称长度有些长,而系统默认显示一行,显示不下就省略号显示,由于页面高度有多余的,所以要求显示全app名称,这就需要看哪 ...

  6. Android 10.0 Launcher3 单层app列表页排序功能实现

    1.概述 在定制化开发中,对于Launcher3的功能定制也是好多的,而对于单层app列表页来说排序功能的开发,也是常有的功能这就需要了解加载app数据的流程,然后根据需要进行排序就可以了, 如图: ...

  7. 基于android记事本毕业论文,基于Android的记事本应用的设计与实现-毕业论文.doc...

    基于Android的记事本应用的设计与实现-毕业论文 毕 业 设 计 说 明 书 课题名称基于Android的记事本应用的设计与实现院 系计算机与软件学院专 业计算机多媒体技术班 级计媒1011学 号 ...

  8. android简单记事本

    android简单记事本 近段学习数据存储写个小程序,简单记事本,实现点击查看删除,添加保存.闲话不多说直接步入正题. 一.上图看着更直观. 1.这是该程序的主界面.上边是一个Button,下边是Li ...

  9. Android TV开发总结(四)通过RecycleView构建一个TV app列表页(仿腾讯视频TV版)

    转载请把头部出处链接和尾部二维码一起转载,本文出自逆流的鱼yuiop:http://blog.csdn.net/hejjunlin/article/details/52854131 前言:昨晚看锤子手 ...

最新文章

  1. java去除字符串的html标签
  2. ASP.NET MVC教程六:两个配置文件详解
  3. 从支付宝SDK的支付流程理解什么是公钥和私钥,什么是加密和数字签名
  4. Vue自定义插件方法大全
  5. java原码、补码、反码总结
  6. 计算机应用怎么写,计算机应用专业描述怎么写
  7. java文档注释——生成帮助文档
  8. echarts2 的引入方式
  9. 产品分析 | K12在线教育之猿辅导
  10. 杨辉三角形算法php实现,PHP实现杨辉三角形
  11. 【未解决】vcs在服务器无法使用——22-03-07工作笔记
  12. Java代码清除Word文档的批注和修订 (Aspose.Words) Java老铁们,亲测有效!
  13. Allegro可供产品包含L、XL和GXL三个级别
  14. ROS,Ubuntu,noobs,raspbian和raspbeery pi3的关系
  15. 【学习笔记】第五章 线性规划
  16. 如何选择PMP、IPMP、CPMP?
  17. IDEA背景颜色设置问题
  18. 计算机实战项目之 [含论文+辩论PPT+源码等]小程序食堂订餐点餐项目+后台管理|前后分离VUE[包运行成功
  19. 可行性分析,实用模板。
  20. 安卓/电脑扑克识别方案源码讲解(含源码在最后)

热门文章

  1. Vue 大屏适配方案2 锁定宽高比
  2. 外贸业务员怎样能提高自己的工作能力?
  3. 无法启动虚拟机,因为虚拟机监控程序未运行
  4. 0ctf-2018 heapstorm2详解
  5. 埃森哲2021财年第二季度全球营收121亿美元,同比增长8%
  6. SEO时关键词应该怎么选
  7. Java中super方法的使用
  8. POJ 3233 Matrix Power Serie (矩阵快速幂)
  9. Linux—更换国内镜像源
  10. QT-自定义日历小工具,支持在线获取左右铭和图片