课程作业需要,于是忙活好几天抄了一个简单的记事本,使用已学内容包括Android UI布局,Activity的跳转,SQLite数据库。
开发环境:Android Studio
参考:https://blog.csdn.net/zouguo1211/article/details/83474845
源码链接:https://github.com/zsy0216/Notepad
目录
写在前面
一.界面预览
二.基本实现
初始界面功能,最上方标题下为用户创建的各条记录,点击进行修改,长按删除,最下方有添加笔记按钮进行笔记的增加操作。实现的布局文件有初始界面activity_main.xml(里面包含可以以列表的形式展示数据内容的ListView控件)、note_item(ListView对应的item布局,以显示每个条目信息)、note_editor(新建文本编辑界面)、activity_show(文本修改界面)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#eaeaea" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Notepad" android:textSize="20sp" android:textStyle="bold" android:background="#efdede" android:paddingTop="10dp" android:paddingBottom="5dp" android:paddingLeft="10dp" android:gravity="left"> </TextView> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:background="#eaeaea" android:layout_weight="1"> <ListView android:id="@+id/lv_note" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp"> </ListView> </LinearLayout> <Button android:id="@+id/btn_add" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:layout_marginBottom="10dp" android:textSize="20sp" android:text="添加笔记"/> </LinearLayout>note_item.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="match_parent" android:orientation="vertical"> <TextView android:id="@+id/tv_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:lines="1" android:text="" android:textStyle="bold" android:textAppearance="?android:attr/textAppearanceLarge"/> <TextView android:id="@+id/tv_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:lines="1"/> <TextView android:id="@+id/tv_time" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:text="" /> </LinearLayout>note_editor.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="match_parent" android:background="#eaeaea" android:orientation="vertical"> <EditText android:id="@+id/et_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="请输入标题"> <requestFocus /> </EditText> <TextView android:id="@+id/edit_time" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#d7d5d5" android:gravity="right" android:textSize="10sp"/> <EditText android:id="@+id/et_content" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:hint="请输入内容" android:gravity="left"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center"> <Button android:id="@+id/btn_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="10dp" android:text="保存" android:textSize="20sp"/> <Button android:id="@+id/btn_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="10dp" android:text="取消" android:textSize="20sp"/> </LinearLayout> </LinearLayout>activity_show.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="match_parent" android:orientation="vertical"> <EditText android:id="@+id/show_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="标题"> <requestFocus /> </EditText> <TextView android:id="@+id/show_time" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="right" android:textSize="10sp"/> <EditText android:id="@+id/show_content" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:hint="内容" android:gravity="left"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center"> <Button android:id="@+id/show_save" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="10dp" android:text="保存" android:textSize="20sp"/> <Button android:id="@+id/show_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginBottom="10dp" android:text="取消" android:textSize="20sp"/> </LinearLayout> </LinearLayout> 功能实现首先SQLite数据库的创建。新建一个DBService类继承自SQLiteOpenHelper,设置静态常量属性,表名、id、标题、内容、创建时间。
DBService.java
package zut.edu.cn.notepad; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBService extends SQLiteOpenHelper { public static final String TABLE = "notes"; public static final String ID = "_id"; public static final String TITLE ="title"; public static final String CONTENT = "content"; public static final String TIME = "time"; public DBService(Context context) { super(context,"notepad.db",null,1); } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE "+TABLE+"( "+ID+ " INTEGER PRIMARY KEY AUTOINCREMENT, "+ TITLE +" VARCHAR(30) ,"+ CONTENT + " TEXT , "+ TIME + " DATETIME NOT NULL )"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }MainActivity.java
package zut.edu.cn.notepad; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { DBService myDb; private Button mBtnAdd; private ListView lv_note; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //实例化自己创建的数据库类 myDb = new DBService(this); //初始化函数 init(); } public void init(){ mBtnAdd = findViewById(R.id.btn_add); lv_note = findViewById(R.id.lv_note); //创建Values类型的list保存数据库中的数据 List<Values> valuesList = new ArrayList<>(); //获得可读SQLiteDatabase对象 SQLiteDatabase db = myDb.getReadableDatabase(); //查询数据库中的数据 Cursor cursor = db.query(DBService.TABLE,null,null, null,null,null,null); if(cursor.moveToFirst()){ Values values; while (!cursor.isAfterLast()){ //实例化values对象 values = new Values(); //把数据库中的一个表中的数据赋值给values values.setId(Integer.valueOf(cursor.getString(cursor.getColumnIndex(DBService.ID)))); values.setTitle(cursor.getString(cursor.getColumnIndex(DBService.TITLE))); values.setContent(cursor.getString(cursor.getColumnIndex(DBService.CONTENT))); values.setTime(cursor.getString(cursor.getColumnIndex(DBService.TIME))); //将values对象存入list对象数组中 valuesList.add(values); cursor.moveToNext(); } } cursor.close(); db.close(); //设置list组件adapter final MyBaseAdapter myBaseAdapter = new MyBaseAdapter(valuesList,this,R.layout.note_item); lv_note.setAdapter(myBaseAdapter); //按钮点击事件 mBtnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, zut.edu.cn.notepad.EditActivity.class); startActivity(intent); } }); //单击查询 lv_note.setOnItemClickListener(new AdapterView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(MainActivity.this,ShowActivity.class); Values values = (Values) lv_note.getItemAtPosition(position); intent.putExtra(DBService.TITLE,values.getTitle().trim()); intent.putExtra(DBService.CONTENT,values.getContent().trim()); intent.putExtra(DBService.TIME,values.getTime().trim()); intent.putExtra(DBService.ID,values.getId().toString().trim()); startActivity(intent); } }); //长按删除 lv_note.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { final Values values = (Values) lv_note.getItemAtPosition(position); new AlertDialog.Builder(MainActivity.this) .setTitle("提示框") .setMessage("是否删除?") .setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SQLiteDatabase db = myDb.getWritableDatabase(); db.delete(DBService.TABLE,DBService.ID+"=?",new String[]{String.valueOf(values.getId())}); db.close(); myBaseAdapter.removeItem(position); lv_note.post(new Runnable() { @Override public void run() { myBaseAdapter.notifyDataSetChanged(); } }); //MainActivity.this.onResume(); } }) .setNegativeButton("no",null).show(); return true; } }); } //创建继承自BaseAdapter的实现类进行ListView的展示 class MyBaseAdapter extends BaseAdapter{ private List<Values> valuesList; private Context context; private int layoutId; public MyBaseAdapter(List<Values> valuesList, Context context, int layoutId) { this.valuesList = valuesList; this.context = context; this.layoutId = layoutId; } @Override public int getCount() { if (valuesList != null && valuesList.size() > 0) return valuesList.size(); else return 0; } @Override public Object getItem(int position) { if (valuesList != null && valuesList.size() > 0) return valuesList.get(position); else return null; } @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.from( getApplicationContext()).inflate(R.layout.note_item, parent, false); viewHolder = new ViewHolder(); viewHolder.title = (TextView) convertView.findViewById(R.id.tv_title); viewHolder.content = convertView.findViewById(R.id.tv_content); viewHolder.time = (TextView) convertView.findViewById(R.id.tv_time); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String title = valuesList.get(position).getTitle(); String content = valuesList.get(position).getContent(); viewHolder.title.setText(title); viewHolder.content.setText(content); viewHolder.time.setText(valuesList.get(position).getTime()); return convertView; } public void removeItem(int position){ this.valuesList.remove(position); } } class ViewHolder{ TextView title; TextView content; TextView time; } }Values.java
Values类实现对数据的保存
package zut.edu.cn.notepad; public class Values { private Integer id; private String title; private String content; private String time; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } @Override public String toString() { return "Values{" + "id=" + id + ", title='" + title + '\'' + ", content='" + content + '\'' + ", time='" + time + '\'' + '}'; } }Edit_Activity.java
package zut.edu.cn.notepad; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Date; public class EditActivity extends AppCompatActivity { DBService myDb; private Button btnCancel; private Button btnSave; private EditText titleEditText; private EditText contentEditText; private TextView timeTextView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.note_editor); init(); if(timeTextView.getText().length()==0) timeTextView.setText(getTime()); } private void init() { myDb = new DBService(this); SQLiteDatabase db = myDb.getReadableDatabase(); titleEditText = findViewById(R.id.et_title); contentEditText = findViewById(R.id.et_content); timeTextView = findViewById(R.id.edit_time); btnCancel = findViewById(R.id.btn_cancel); btnSave = findViewById(R.id.btn_save); //按钮点击事件 btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(EditActivity.this,MainActivity.class); startActivity(intent); } }); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase db = myDb.getWritableDatabase(); ContentValues values = new ContentValues(); String title= titleEditText.getText().toString(); String content=contentEditText.getText().toString(); String time= timeTextView.getText().toString(); if("".equals(titleEditText.getText().toString())){ Toast.makeText(EditActivity.this,"标题不能为空",Toast.LENGTH_LONG).show(); return; } if("".equals(contentEditText.getText().toString())) { Toast.makeText(EditActivity.this,"内容不能为空",Toast.LENGTH_LONG).show(); return; } values.put(DBService.TITLE,title); values.put(DBService.CONTENT,content); values.put(DBService.TIME,time); db.insert(DBService.TABLE,null,values); Toast.makeText(EditActivity.this,"保存成功",Toast.LENGTH_LONG).show(); Intent intent = new Intent(EditActivity.this,MainActivity.class); startActivity(intent); db.close(); } }); } //获取当前时间 private String getTime() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(System.currentTimeMillis()); String str = sdf.format(date); return str; } }ShowActivity
package zut.edu.cn.notepad; import android.annotation.SuppressLint; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.text.SimpleDateFormat; import java.util.Date; public class ShowActivity extends AppCompatActivity { private Button btnSave; private Button btnCancel; private TextView showTime; private EditText showContent; private EditText showTitle; private Values value; DBService myDb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_show); init(); } public void init() { myDb = new DBService(this); btnCancel = findViewById(R.id.show_cancel); btnSave = findViewById(R.id.show_save); showTime = findViewById(R.id.show_time); showTitle = findViewById(R.id.show_title); showContent = findViewById(R.id.show_content); Intent intent = this.getIntent(); if (intent != null) { value = new Values(); value.setTime(intent.getStringExtra(DBService.TIME)); value.setTitle(intent.getStringExtra(DBService.TITLE)); value.setContent(intent.getStringExtra(DBService.CONTENT)); value.setId(Integer.valueOf(intent.getStringExtra(DBService.ID))); showTime.setText(value.getTime()); showTitle.setText(value.getTitle()); showContent.setText(value.getContent()); } //按钮点击事件 btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SQLiteDatabase db = myDb.getWritableDatabase(); ContentValues values = new ContentValues(); String content = showContent.getText().toString(); String title = showTitle.getText().toString(); values.put(DBService.TIME, getTime()); values.put(DBService.TITLE,title); values.put(DBService.CONTENT,content); db.update(DBService.TABLE,values,DBService.ID+"=?",new String[]{value.getId().toString()}); Toast.makeText(ShowActivity.this,"修改成功",Toast.LENGTH_LONG).show(); db.close(); Intent intent = new Intent(ShowActivity.this,MainActivity.class); startActivity(intent); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String content = showContent.getText().toString(); final String title = showTitle.getText().toString(); new AlertDialog.Builder(ShowActivity.this) .setTitle("提示框") .setMessage("是否保存当前内容?") .setPositiveButton("yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { SQLiteDatabase db = myDb.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(DBService.TIME, getTime()); values.put(DBService.TITLE,title); values.put(DBService.CONTENT,content); db.update(DBService.TABLE,values,DBService.ID+"=?",new String[]{value.getId().toString()}); Toast.makeText(ShowActivity.this,"修改成功",Toast.LENGTH_LONG).show(); db.close(); Intent intent = new Intent(ShowActivity.this,MainActivity.class); startActivity(intent); } }) .setNegativeButton("no", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(ShowActivity.this,MainActivity.class); startActivity(intent); } }).show(); } }); } String getTime() { @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm"); //获取当前时间 Date date = new Date(System.currentTimeMillis()); return simpleDateFormat.format(date); } }偷偷地写在最后
基本实现就是以上了,还有很多地方不太完善,希望能够从一次一次的实践当中学习到更多的东西。
曾经沧海难为水,除却巫山不是云。
源码已上传:github.Notepad