Android记事本——记事本记事列表页实现

实现效果:

在这里插入图片描述

实现的功能:

查看记事列表:登录成功后,系统进入第二个活动,系统查询数据库里面所有的记事项,如记事标题/内容/时间,将查询到的信息存放在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.SwipeRefreshLayout
        android:layout_below ="@+id/title_bar"
        android:id="@+id/swipe_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="20dp">
        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:orientation="vertical"
            >
            <ListView
                android:id="@+id/note_list"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
            </ListView>
            <TextView
            android: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>

    <Button
        android: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" />

    <Button
        android: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" />

    <Button
        android: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" />

    <Button
        android: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">
<ImageView
    android:id="@+id/rand_icon"
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:background="@drawable/book"
    android:padding="2dp"
    android:layout_margin="4dp" />
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="0.6"
        android:weightSum="1"
        android:orientation="horizontal">
        <TextView
            android: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"/>
        <TextView
            android: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>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_marginLeft="8dp"
        android:layout_weight="0.4"
        android:weightSum="1"
        android:orientation="horizontal">
        <TextView
            android: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"/>
        <TextView
            android: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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="center"
        android:orientation="horizontal"
        android:weightSum="1">

        <EditText
            android: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" />
        <Button
            android: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);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        //具体表的创建
        Note.getInstance().onCreate(db);
    }
    @Override
    public 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;
    }

    //实现表的创建
    @Override
    public 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);
    }

    //实现表的更新
    @Override
    public 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 setter

    public 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);
    }

    @Override
    public int getCount() {
        return noteList.size();
    }

    @Override
    public Object getItem(int position) {
        return noteList.get(position).getTitle();
    }

    @Override
    public long getItemId(int position) {
        return Long.parseLong(noteList.get(position).getId());
    }

    public void remove(int index){
        noteList.remove(index);
    }

    public void refreshDataSet(){
        notifyDataSetChanged();
    }

    @Override
    public 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;

    @Override
    protected 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格式转为byte
        photobyte = 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() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(NoteEditorActivity.this)
                        .setIcon(R.drawable.picture)
                        .setMessage("插入图片")
                        .setPositiveButton(R.string.photograph, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                takePhoto();
                            }
                        }).setNegativeButton(R.string.photo_album, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        chooseFromAlbum();//  用户授权了权限申请之后就会调用该方法
                    }
                }).create().show();
            }
        });
        btn_return.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public 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();
                }
            }
        });
    }


    @Override
    public 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() {
                            @Override
                            public 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() {
                            @Override
                            public 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();
    }

    @Override
    public 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());
    }

    @Override
    public 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();
        //设定类型为image
        intent.setType("image/*");
        //设置action
        intent.setAction(Intent.ACTION_GET_CONTENT);
        //选中相片后返回本Activity
        startActivityForResult(intent, 1);
    }

    @Override
    protected 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 block
                    e.printStackTrace();
                }
            }
            //如果选择的是拍照
            if (requestCode == 2) {
                System.out.println("-----fjwefowefwef");
                try {
                    if (uri != null)
                        //这个方法是根据Uri获取Bitmap图片的静态方法
                        bitmap = MediaStore.Images.Media.getBitmap(cr, uri);
                        //这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
                    else
                        extras = data.getExtras();
                    bitmap = extras.getParcelable("data");
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.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转变为 byte
     public  byte[] imgtobyte(Bitmap bitmap) {
//        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);
        return baos.toByteArray();
    }

    //把图片转变为字节 drawable转变为byte
    public 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;
    }
}

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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值