一、搭建记事本页面布局
1.创建项目
创建一个名为Notepad的项目,Activity名称为NotepadActivity,布局文件名称为activity_notepad。
2.导入界面图片
3.放置界面控件
activity_notepad.xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FEFEFE">
<TextView
android:id="@+id/note_name"
android:layout_width="match_parent"
android:layout_height="45dp"
android:textSize="20sp"
android:textColor="@android:color/white"
android:gravity="center"
android:textStyle="bold"
android:background="#FB7A6A"
android:text="记事本" />
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#00000000"
android:divider="#E4E4E4"
android:dividerHeight="1dp"
android:fadingEdge="none"
android:listSelector="#00000000"
android:scrollbars="none"
android:layout_below="@+id/note_name" >
</ListView>
<ImageView
android:id="@+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/add"
android:layout_marginBottom="30dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
4.修改清单文件
android:theme="@style/Theme.AppCompat.NoActionBar"
二、搭建记事本界面Item布局
1.创建记事本界面Item布局文件
在res/layout文件夹中,创建一个布局文件notepad_item_layout.xml
2.放置界面控件
notepad_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="12dp">
<TextView
android:id="@+id/item_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="2"
android:ellipsize="end"
android:lineSpacingExtra="3dp"
android:paddingTop="10dp"
android:textColor="@android:color/black" />
<TextView
android:id="@+id/item_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FB7A6A"
android:paddingTop="5dp"
android:paddingBottom="7dp" />
</LinearLayout>
三、封装记录信息实体类
NotepadBean.java
package com.example.notepad.bean;
public class NotepadBean {
private String id;
private String notepadContent;
private String notepadTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNotepadContent() {
return notepadContent;
}
public void setNotepadContent(String notepadContent) {
this.notepadContent = notepadContent;
}
public String getNotepadTime() {
return notepadTime;
}
public void setNotepadTime(String notepadTime) {
this.notepadTime = notepadTime;
}
}
四、编写记事本页面列表适配器
1.创建NotepadAdapter
2.创建ViewHolder类
在NotepadAdapter类中创建一个ViewHolder类
NotepadAdapter.java
package com.example.notepad.adapter;
......//省略导入包
public class NotepadAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private List<NotepadBean> list;
public NotepadAdapter(Context context, List<NotepadBean> list){
this.layoutInflater = LayoutInflater.from(context);
this.list = list;
}
@Override
public int getCount() {
return list == null ? 0 : list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
convertView = layoutInflater.inflate(R.layout.notepad_item_layout, null);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
NotepadBean noteInfo = (NotepadBean) getItem(position);
viewHolder.tvNotepadContent.setText(noteInfo.getNotepadContent());
viewHolder.tvNotepadTime.setText(noteInfo.getNotepadTime());
return convertView;
}
class ViewHolder{
TextView tvNotepadContent;
TextView tvNotepadTime;
public ViewHolder(View view){
tvNotepadContent = view.findViewById(R.id.item_content);
tvNotepadTime = view.findViewById(R.id.item_time);
}
}
}
五、创建数据库
1.创建DBUtils类
DBUtils.java
package com.example.notepad.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DBUtils {
public static final String DATABASE_NAME = "NotepadPlus"; //数据库名
public static final String DATABASE_TABLE = "notePlus"; //表名
public static final int DATABASE_VERSION = 1; //数据库版本
//数据表列名
public static final String NOTE_ID ="id";
public static final String NOTE_CONTENT ="content";
public static final String NOTE_TIME ="time";
//获取当前时间
public static final String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
return sdf.format(date);
}
}
2.创建SQLiteHelper类
SQLiteHelper.java
package com.example.notepad.database;
......//省略导入包
import java.util.List;
public class SQLiteHelper extends SQLiteOpenHelper {
private SQLiteDatabase sqLiteDatabase;
public SQLiteHelper(Context context) {
super(context, DBUtils.DATABASE_NAME, null, DBUtils.DATABASE_VERSION);
sqLiteDatabase = this.getWritableDatabase();
}
//创建数据库
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DBUtils.DATABASE_TABLE + "(" + DBUtils.NOTE_ID +
" INTEGER PRIMARY KEY AUTOINCREMENT," + DBUtils.NOTE_CONTENT +
" TEXT," + DBUtils.NOTE_TIME + " TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
//添加数据
public boolean insertData(String userContent, String userTime) {
ContentValues values = new ContentValues();
values.put(DBUtils.NOTE_CONTENT, userContent);
values.put(DBUtils.NOTE_TIME, userTime);
return sqLiteDatabase.insert(DBUtils.DATABASE_TABLE, null, values) > 0;
}
//删除数据
public boolean deleteData(String id) {
String sql = DBUtils.NOTE_ID + "=?";
String[] contentValuesArrary = new String[]{String.valueOf(id)};
return sqLiteDatabase.delete(DBUtils.DATABASE_TABLE, sql, contentValuesArrary) > 0;
}
//修改数据
public boolean updateData(String id, String content, String userYear) {
ContentValues contentValues = new ContentValues();
contentValues.put(DBUtils.NOTE_CONTENT, content);
contentValues.put(DBUtils.NOTE_TIME, userYear);
String sql = DBUtils.NOTE_ID + "=?";
String[] strings = new String[]{id};
return sqLiteDatabase.update(DBUtils.DATABASE_TABLE, contentValues, sql, strings) > 0;
}
//查询数据
public List<NotepadBean> qurry() {
List<NotepadBean> list = new ArrayList<NotepadBean>();
Cursor cursor = sqLiteDatabase.query(DBUtils.DATABASE_TABLE, null, null, null,
null, null, DBUtils.NOTE_ID + " desc");
if (cursor != null) {
while (cursor.moveToNext()) {
NotepadBean noteInfo = new NotepadBean();
String id = String.valueOf(cursor.getInt
(cursor.getColumnIndex(DBUtils.NOTE_ID)));
String content = cursor.getString(cursor.getColumnIndex
(DBUtils.NOTE_CONTENT));
String time = cursor.getString(cursor.getColumnIndex(DBUtils.NOTE_TIME));
noteInfo.setId(id);
noteInfo.setNotepadContent(content);
noteInfo.setNotepadTime(time);
list.add(noteInfo);
}
cursor.close();
}
return list;
}
}
六、实现记事本界面的显示功能
NotepadActivity.java
package com.example.notepad;
......//省略导入包
public class NotepadActivity extends Activity {
ListView listView;
SQLiteHelper mSQLiteHelper;
List<NotepadBean> list;
NotepadAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notepad);
//用于显示记录的列表
listView = (ListView) findViewById(R.id.listview);
ImageView add = (ImageView) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(NotepadActivity.this,RecordActivity.class);
startActivityForResult(intent,1);
}
});
initData();
}
protected void initData(){
mSQLiteHelper = new SQLiteHelper(this);
showQueryData();
}
private void showQueryData(){
if (list != null) {
list.clear();
}
//从数据库中查询数据(保存的记录)
list = mSQLiteHelper.qurry();
adapter = new NotepadAdapter(this, list);
listView.setAdapter(adapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1&&resultCode == 2){
showQueryData();
}
}
}
七、搭建添加记录界面和修改记录界面的布局
1.创建添加记录界面和修改记录界面
创建一个名为RecordActivity的Activity并将布局文件名指定为activity_record
2.放置页面控件
activity_record.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FEFEFE">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="#FB7A6A"
android:orientation="horizontal">
<ImageView
android:id="@+id/note_back"
android:layout_width="45dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:paddingLeft="11dp"
android:src="@drawable/back" />
<TextView
android:id="@+id/note_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:text="添加记录"
android:textColor="@android:color/white"
android:textSize="15sp"
android:textStyle="bold" />
</RelativeLayout>
<TextView
android:id="@+id/tv_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15sp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:gravity="center"
android:visibility="gone"
android:textColor="#FB7A6A" />
<EditText
android:id="@+id/note_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="top"
android:hint="请输入要添加的内容"
android:paddingLeft="5dp"
android:textColor="@android:color/black"
android:background="#FEFEFE" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#FB7A6A" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/delete"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:src="@drawable/delete"
android:paddingBottom="15dp"
android:paddingTop="9dp" />
<ImageView
android:id="@+id/note_save"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:src="@drawable/save_note"
android:paddingBottom="15dp"
android:paddingTop="9dp" />
</LinearLayout>
</LinearLayout>
八、实现添加记录界面的功能
RecordActivity.java
package com.example.notepad;
......//省略导入包
public class RecordActivity extends Activity implements View.OnClickListener {
ImageView note_back;
TextView note_time;
EditText content;
ImageView delete;
ImageView note_save;
SQLiteHelper mSQLiteHelper;
TextView noteName;
String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
note_back = (ImageView) findViewById(R.id.note_back); //后退键
note_time = (TextView) findViewById(R.id.tv_time); //保存记录的时间
content = (EditText) findViewById(R.id.note_content); //记录的内容
delete = (ImageView) findViewById(R.id.delete); //清空的按钮
note_save = (ImageView) findViewById(R.id.note_save); //保存的按钮
noteName = (TextView) findViewById(R.id.note_name); //标题的名称
note_back.setOnClickListener(this);
delete.setOnClickListener(this);
note_save.setOnClickListener(this);
initData();
}
protected void initData() {
mSQLiteHelper = new SQLiteHelper(this);
noteName.setText("添加记录");
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.note_back: //后退键的点击事件
finish();
break;
case R.id.delete: //"清空"按钮的点击事件
content.setText("");
break;
case R.id.note_save: //"保存"按钮的点击事件
//获取输入内容
String noteContent = content.getText().toString().trim();
//向数据库中添加数据
if (noteContent.length() > 0) {
if (mSQLiteHelper.insertData(noteContent, DBUtils.getTime())) {
showToast("保存成功");
setResult(2);
finish();
} else {
showToast("保存失败");
}
} else {
showToast("修改内容不能为空!");
}
break;
}
}
public void showToast(String message){
Toast.makeText(RecordActivity.this, message, Toast.LENGTH_SHORT).show();
}
}
九、实现修改记录界面的功能
1.实现查看记录功能
在NotepadActivity的initData()方法中添加跳转到修改记录界面的逻辑代码。
protected void initData(){
......
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
NotepadBean notepadBean = list.get(position);
Intent intent = new Intent(NotepadActivity.this, RecordActivity.class);
intent.putExtra("id", notepadBean.getId());
intent.putExtra("time", notepadBean.getNotepadTime());
//记录的内容
intent.putExtra("content", notepadBean.getNotepadContent());
//跳转到修改记录界面
NotepadActivity.this.startActivityForResult(intent, 1);
}
});
在RecordActivity的initData()方法中需要接收记事本界面传递过来的记录数据并将数据显示到界面上。
protected void initData() {
......
Intent intent = getIntent();
if (intent != null) {
id = intent.getStringExtra("id");
if (id != null) {
noteName.setText("修改记录");
content.setText(intent.getStringExtra("content"));
note_time.setText(intent.getStringExtra("time"));
note_time.setVisibility(View.VISIBLE);
}
}
}
2.实现修改记录功能
在RecordActivity中的onClick()方法中。
public void onClick(View view) {
switch (view.getId()) {
......
case R.id.note_save: //"保存"按钮的点击事件
//获取输入内容
String noteContent = content.getText().toString().trim();
//修改页面的保存操作
if (id != null) {
if (noteContent.length() > 0) {
if (mSQLiteHelper.updateData(id, noteContent, DBUtils.getTime())) {
showToast("修改成功");
setResult(2);
finish();
} else {
showToast("修改失败");
}
} else {
showToast("修改记录的内容不能为空!");
}
} else {
//向数据库中添加数据
if (noteContent.length() > 0) {
if (mSQLiteHelper.insertData(noteContent, DBUtils.getTime())) {
showToast("保存成功");
setResult(2);
finish();
} else {
showToast("保存失败");
}
} else {
showToast("修改内容不能为空!");
}
}
break;
}
}
十、删除记事本中的记录
在NotepadActivity中的initData()方法中添加删除记录的逻辑代码。
protected void initData(){
......
//删除记录功能
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog dialog;
AlertDialog.Builder builder = new AlertDialog.Builder(NotepadActivity.this)
.setMessage("是否删除此记录?")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
NotepadBean notepadBean = list.get(position);
if (mSQLiteHelper.deleteData(notepadBean.getId())) {
list.remove(position); //删除对应的Item
adapter.notifyDataSetChanged(); //更新记事本界面
Toast.makeText(NotepadActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); //关闭对话框
}
});
dialog = builder.create(); //创建对话框
dialog.show(); //显示对话框
return true;
}
});
}