0


Android——记事本功能业务(完整代码)

实现效果

一、搭建记事本页面布局activity_notepad.xml

1.创建项目

项目名为Notepad,指定包名为cn.itcast.notepad

Activity名称为NotepadActivity,布局文件名为activity_notepad

2.导入图片到res文件夹下面 一个新建的文件夹drawable-hdpi中

3.页面代码如下

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:background="#fefefe">
  7. <TextView
  8. android:id="@+id/note_name"
  9. android:layout_width="match_parent"
  10. android:layout_height="45dp"
  11. android:textSize="20sp"
  12. android:textColor="@android:color/white"
  13. android:gravity="center"
  14. android:textStyle="bold"
  15. android:background="#fb7a6a"
  16. android:text="记事本"/>
  17. <ListView
  18. android:id="@+id/listview"
  19. android:layout_width="match_parent"
  20. android:layout_height="match_parent"
  21. android:cacheColorHint="#00000000"
  22. android:divider="#E4E4E4"
  23. android:dividerHeight="1dp"
  24. android:fadingEdge="none"
  25. android:listSelector="#00000000"
  26. android:scrollbars="none"
  27. android:layout_below="@+id/note_name">
  28. </ListView>
  29. <ImageView
  30. android:id="@+id/add"
  31. android:layout_width="wrap_content"
  32. android:layout_height="wrap_content"
  33. android:src="@drawable/add"
  34. android:layout_marginBottom="30dp"
  35. android:layout_alignParentBottom="true"
  36. android:layout_centerHorizontal="true"/>
  37. </RelativeLayout>

4.修改清单文件

项目创建后所有界面最上方都有一个绿色的默认标题栏,不美观。在AndroidManifest.xml修改代码去掉标题栏。 在<application>标签中修改为:

  1. android:theme="@style/Theme.AppCompat.NoActionBar"

二、搭建记事本界面Item布局notepad_item_layout.xml

由于记事本界面使用了ListView控件展示记录列表,因此需要创建一个该列表的Item界面。

1.创建布局文件

res/layout文件夹中,右击【NEW】-【XML】-【Layout XML File】,名字为notepad_item_layout

2.布局notepad_item_layout.xml界面

放置两个TextView控件,分别用于显示记录的部分内容与保存的时间。

代码如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout
  3. xmlns:android="http://schemas.android.com/apk/res/android"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:background="#fefefe">
  7. <TextView
  8. android:id="@+id/note_name"
  9. android:layout_width="match_parent"
  10. android:layout_height="45dp"
  11. android:textSize="20sp"
  12. android:textColor="@android:color/white"
  13. android:gravity="center"
  14. android:textStyle="bold"
  15. android:background="#fb7a6a"
  16. android:text="记事本"/>
  17. <ListView
  18. android:id="@+id/listview"
  19. android:layout_width="match_parent"
  20. android:layout_height="match_parent"
  21. android:cacheColorHint="#00000000"
  22. android:divider="#E4E4E4"
  23. android:dividerHeight="1dp"
  24. android:fadingEdge="none"
  25. android:listSelector="#00000000"
  26. android:scrollbars="none"
  27. android:layout_below="@+id/note_name">
  28. </ListView>
  29. <ImageView
  30. android:id="@+id/add"
  31. android:layout_width="wrap_content"
  32. android:layout_height="wrap_content"
  33. android:src="@drawable/add"
  34. android:layout_marginBottom="30dp"
  35. android:layout_alignParentBottom="true"
  36. android:layout_centerHorizontal="true"/>
  37. </RelativeLayout>

三、封装记录信息实体类NotepadBean类

创建一个NotepadBean类,存放每个记录的记录内容和保存时间属性。

1.选中cn.itcast.notepad包,右击-【New】-【Package】,命名为bean,创建一个bean包。

在该包中,右击-【New】-【JavaClass】,命名为NotepadBean。

2.NotepadBean.java代码如下

  1. package cn.itcast.notepad.bean;
  2. public class NotepadBean {
  3. private String id; //记录的id
  4. private String notepadContent; //记录的内容
  5. private String notepadTime; //保存记录的时间
  6. //右击-【Generate】-【Getter and Setter】,产生下面代码
  7. public String getId() {
  8. return id;
  9. }
  10. public void setId(String id) {
  11. this.id = id;
  12. }
  13. public String getNotepadContent() {
  14. return notepadContent;
  15. }
  16. public void setNotepadContent(String notepadContent) {
  17. this.notepadContent = notepadContent;
  18. }
  19. public String getNotepadTime() {
  20. return notepadTime;
  21. }
  22. public void setNotepadTime(String notepadTime) {
  23. this.notepadTime = notepadTime;
  24. }
  25. }

四、编写记事本界面列表适配器NotepadAdapter类

创建数据适配器NotepadAdapter对ListView控件进行数据适配。

1.选中cn.itcast.notepad包,右击-【New】-【Package】,命名为adapter。

在该包中,右击-【New】-【JavaClass】,命名为NotepadAdapter。

2.(1)NotepadAdapter类继承自BaseAdapter类,然后点击【Alt】+【Enter】,【implement methods】重写方法getCount()、getItem()、 getItemId()、getView()。

(2)创建构造方法

  1. public NotepadAdapter(Context context, List<NotepadBean> list)

通过inflate()方法加载Item界面的布局文件。

  1. private LayoutInflater layoutInflater;
  2. private List<NotepadBean> list;
  3. public NotepadAdapter(Context context, List<NotepadBean> list){
  4. this.layoutInflater=LayoutInflater.from(context);
  5. this.list=list;
  6. }

(3)创建ViewHolder类

在类里面创建构造方法,在该方法中初始化Item界面(即notepad_item_layout.xml)上的控件。

  1. public ViewHolder(View view){
  2. tvNoteoadContent=(TextView) view.findViewById(R.id.item_content);
  3. tvNotepadTime=(TextView) view.findViewById(R.id.item_time);
  4. }

接着继续在getView方法里面写代码

3.代码如下:

  1. package cn.itcast.notepad.adapter;
  2. import android.content.Context;
  3. import android.view.LayoutInflater;
  4. import android.view.View;
  5. import android.view.ViewGroup;
  6. import android.widget.BaseAdapter;
  7. import android.widget.TextView;
  8. import java.util.List;
  9. import cn.itcast.notepad.R;
  10. import cn.itcast.notepad.bean.NotepadBean;
  11. public class NotepadAdapter extends BaseAdapter{
  12. private LayoutInflater layoutInflater;
  13. private List<NotepadBean> list;
  14. public NotepadAdapter(Context context, List<NotepadBean> list){
  15. this.layoutInflater=LayoutInflater.from(context);
  16. this.list=list;
  17. }
  18. @Override
  19. public int getCount() {
  20. return list==null ? 0 : list.size();
  21. }
  22. @Override
  23. public Object getItem(int position) {
  24. return list.get(position);
  25. }
  26. @Override
  27. public long getItemId(int position) {
  28. return position;
  29. }
  30. @Override
  31. public View getView(int position, View convertView, ViewGroup parent) {
  32. ViewHolder viewHolder;
  33. if (convertView==null){
  34. convertView=layoutInflater.inflate(R.layout.notepad_item_layout,null);
  35. viewHolder=new ViewHolder(convertView);
  36. convertView.setTag(viewHolder);
  37. }else {
  38. viewHolder=(ViewHolder) convertView.getTag();
  39. }
  40. NotepadBean noteInfo=(NotepadBean) getItem(position);
  41. viewHolder.tvNoteoadContent.setText(noteInfo.getNotepadContent());
  42. viewHolder.tvNotepadTime.setText(noteInfo.getNotepadTime());
  43. return convertView;
  44. }
  45. class ViewHolder{
  46. TextView tvNoteoadContent;;
  47. TextView tvNotepadTime;
  48. public ViewHolder(View view){
  49. tvNoteoadContent=(TextView) view.findViewById(R.id.item_content);
  50. tvNotepadTime=(TextView) view.findViewById(R.id.item_time);
  51. }
  52. }
  53. }

五、创建数据库

在这个记事本程序中存储和读取记录的数据都是通过操作数据库完成的,因此需要创建数据库类SQLiteHelper和数据库的工具类DBUtils.java。

(一)创建DBUtils类

在该类中定义数据库的名称、表名、数据库版本、数据库表中的列名以及获取当前日期等信息。

1.选中cn.itcast.notepad包,右击-【New】-【Package】,命名为utils。

在该包中,右击-【New】-【JavaClass】,命名为DBUtils。

2.DBUtils.java代码如下

  1. package cn.itcast.notepad.utils;
  2. import java.text.SimpleDateFormat;
  3. import java.util.Date;
  4. public class DBUtils {
  5. public static final String DATABASE_NAME = "Notepad";//数据库名
  6. public static final String DATABASE_TABLE = "Note"; //表名
  7. public static final int DATABASE_VERION = 1; //数据库版本
  8. //数据库表中的列名
  9. public static final String NOTEPAD_ID = "id";
  10. public static final String NOTEPAD_CONTENT = "content";
  11. public static final String NOTEPAD_TIME = "notetime";
  12. //获取当前日期
  13. public static final String getTime(){
  14. SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
  15. Date date = new Date(System.currentTimeMillis());
  16. return simpleDateFormat.format(date);
  17. }
  18. }

(二)创建SQLiteHelper类

创建Notepad的数据库,实现增删改查的功能。

1.选中cn.itcast.notepad包,右击-【New】-【Package】,命名为database。

在该包中,右击-【New】-【JavaClass】,命名为SQLiteHelper。

2.SQLiteHelper.java代码如下

  1. package cn.itcast.notepad.database;
  2. import android.content.ContentValues;
  3. import android.content.Context;
  4. import android.database.Cursor;
  5. import android.database.sqlite.SQLiteDatabase;
  6. import android.database.sqlite.SQLiteOpenHelper;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import cn.itcast.notepad.bean.NotepadBean;
  10. import cn.itcast.notepad.utils.DBUtils;
  11. public class SQLiteHelper extends SQLiteOpenHelper {
  12. private SQLiteDatabase sqLiteDatabase;
  13. //创建数据库
  14. public SQLiteHelper(Context context){
  15. super(context, DBUtils.DATABASE_NAME, null, DBUtils.DATABASE_VERION);//调用了DBUtils类,得到数据库名Notepad
  16. sqLiteDatabase = this.getWritableDatabase();
  17. }
  18. //创建表,用execSQL()方法创建一个数据表,列名分别为ID、CONTENT、TIME
  19. @Override
  20. public void onCreate(SQLiteDatabase db) {
  21. db.execSQL("create table "+DBUtils.DATABASE_TABLE+"("+DBUtils.NOTEPAD_ID+
  22. " integer primary key autoincrement,"+ DBUtils.NOTEPAD_CONTENT +
  23. " text," + DBUtils.NOTEPAD_TIME+ " text)");
  24. }
  25. @Override
  26. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
  27. //添加数据
  28. public boolean insertData(String userContent,String userTime){
  29. ContentValues contentValues=new ContentValues();
  30. contentValues.put(DBUtils.NOTEPAD_CONTENT,userContent);
  31. contentValues.put(DBUtils.NOTEPAD_TIME,userTime);
  32. return
  33. sqLiteDatabase.insert(DBUtils.DATABASE_TABLE,null,contentValues)>0;
  34. }
  35. //删除数据
  36. public boolean deleteData(String id){
  37. String sql=DBUtils.NOTEPAD_ID+"=?";
  38. String[] contentValuesArray=new String[]{String.valueOf(id)};
  39. return
  40. sqLiteDatabase.delete(DBUtils.DATABASE_TABLE,sql,contentValuesArray)>0;
  41. }
  42. //修改数据
  43. public boolean updateData(String id,String content,String userYear){
  44. ContentValues contentValues=new ContentValues();
  45. contentValues.put(DBUtils.NOTEPAD_CONTENT,content);
  46. contentValues.put(DBUtils.NOTEPAD_TIME,userYear);
  47. String sql=DBUtils.NOTEPAD_ID+"=?";
  48. String[] strings=new String[]{id};
  49. return
  50. sqLiteDatabase.update(DBUtils.DATABASE_TABLE,contentValues,sql,strings)>0;
  51. }
  52. //查询数据
  53. public List<NotepadBean> query(){//将遍历的数据存放在一个List<NotepadBean>类型的合集中
  54. List<NotepadBean> list=new ArrayList<NotepadBean>();
  55. // 通过query()方法查询数据库表中的所有数据,并返回一个Cursor对象
  56. Cursor cursor=sqLiteDatabase.query(DBUtils.DATABASE_TABLE,null,null,null,
  57. null,null,DBUtils.NOTEPAD_ID+" desc");
  58. if (cursor!=null){
  59. while (cursor.moveToNext()){//通过while循环遍历Cursor对象中的数据
  60. NotepadBean noteInfo=new NotepadBean();
  61. String id = String.valueOf(cursor.getInt
  62. (cursor.getColumnIndex(DBUtils.NOTEPAD_ID)));
  63. String content = cursor.getString(cursor.getColumnIndex
  64. (DBUtils.NOTEPAD_CONTENT));
  65. String time = cursor.getString(cursor.getColumnIndex
  66. (DBUtils.NOTEPAD_TIME));
  67. noteInfo.setId(id);
  68. noteInfo.setNotepadContent(content);
  69. noteInfo.setNotepadTime(time);
  70. list.add(noteInfo);
  71. }
  72. cursor.close();
  73. }
  74. return list;
  75. }
  76. }

六、实现记事本界面的显示功能NotepadAdapter.java

1.包括显示列表功能和 添加按钮功能

2.步骤

初始化ListView控件,初始化添加按钮

  1. listView = (ListView) findViewById(R.id.listview);
  2. ImageView add = (ImageView) findViewById(R.id.add);

创建initData()方法,在这个方法里初始化需要写入的数据

  1. protected void initData() {
  2. mSQLiteHelper= new SQLiteHelper(this); //创建数据库
  3. showQueryData();
  4. }

创建showQueryData()方法,在这个方法里获取数据库里面的数据,并显示在列表里面。
首先调用query()方法查询数据库中保存的数据,返回值是list的集合。
接着设置一个适配器,将获取的记录数据传递到NotepadAdapter中,需要传入两个参数,一个是上下文的信息,第二个是一个集合。
最后通过setAdapter()方法为ListView控件设置NotepadAdapter适配器。

  1. list = mSQLiteHelper.query();
  2. adapter = new NotepadAdapter(this, list);
  3. listView.setAdapter(adapter);

initData()方法在onCreat()方法中调用一下。

为ImageView设置点击事件
创建intent对象,需传入两个参数,一个是上下文的信息,第二个是跳转的activity的名称。
调用startActivityForResult()方法跳转到添加记录界面。

  1. add.setOnClickListener(new View.OnClickListener() {
  2. @Override
  3. public void onClick(View v) {
  4. Intent intent = new Intent(NotepadActivity.this,
  5. RecordActivity.class);
  6. startActivityForResult(intent, 1);
  7. }
  8. });

重写onActivityResult()方法,当关闭添加记录界面时,调用该方法。

首先判断请求码是否为1 返回码是否为2(这是在添加记录界面设置的),是,调用showQueryData()方法重新获取数据并显示。

  1. protected void onActivityResult(int requestCode,int resultCode, Intent data){
  2. super.onActivityResult(requestCode, resultCode, data);
  3. if (requestCode==1&&resultCode==2){
  4. showQueryData();
  5. }
  6. }

3.NotepadAdapter.java 具体代码如下

  1. package cn.itcast.notepad;
  2. import android.app.Activity;
  3. import android.app.AlertDialog;
  4. import android.content.DialogInterface;
  5. import android.content.Intent;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.AdapterView;
  9. import android.widget.ImageView;
  10. import android.widget.ListView;
  11. import android.widget.Toast;
  12. import java.util.List;
  13. import cn.itcast.notepad.adapter.NotepadAdapter;
  14. import cn.itcast.notepad.bean.NotepadBean;
  15. import cn.itcast.notepad.database.SQLiteHelper;
  16. public class NotepadActivity extends Activity {
  17. ListView listView;
  18. List<NotepadBean> list;
  19. SQLiteHelper mSQLiteHelper;
  20. NotepadAdapter adapter;
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_notepad);
  25. //用于显示便签的列表
  26. listView = (ListView) findViewById(R.id.listview);
  27. ImageView add = (ImageView) findViewById(R.id.add);
  28. add.setOnClickListener(new View.OnClickListener() {
  29. @Override
  30. public void onClick(View v) {
  31. Intent intent = new Intent(NotepadActivity.this,
  32. RecordActivity.class);
  33. startActivityForResult(intent, 1);
  34. }
  35. });
  36. initData();
  37. }
  38. protected void initData() {
  39. mSQLiteHelper= new SQLiteHelper(this); //创建数据库
  40. showQueryData();
  41. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  42. @Override
  43. public void onItemClick(AdapterView<?> parent,View view,int position,long id){
  44. NotepadBean notepadBean = list.get(position);
  45. Intent intent = new Intent(NotepadActivity.this, RecordActivity.class);
  46. intent.putExtra("id", notepadBean.getId());
  47. intent.putExtra("time", notepadBean.getNotepadTime()); //记录的时间
  48. intent.putExtra("content", notepadBean.getNotepadContent()); //记录的内容
  49. NotepadActivity.this.startActivityForResult(intent, 1);
  50. }
  51. });
  52. listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
  53. @Override
  54. public boolean onItemLongClick(AdapterView<?> parent, View view, final int
  55. position, long id) {
  56. AlertDialog dialog;
  57. AlertDialog.Builder builder = new AlertDialog.Builder( NotepadActivity.this)
  58. .setMessage("是否删除此事件?")
  59. .setPositiveButton("确定", new DialogInterface.OnClickListener() {
  60. @Override
  61. public void onClick(DialogInterface dialog, int which) {
  62. NotepadBean notepadBean = list.get(position);
  63. if(mSQLiteHelper.deleteData(notepadBean.getId())){
  64. list.remove(position);
  65. adapter.notifyDataSetChanged();
  66. Toast.makeText(NotepadActivity.this,"删除成功",
  67. Toast.LENGTH_SHORT).show();
  68. }
  69. }
  70. })
  71. .setNegativeButton("取消", new DialogInterface.OnClickListener() {
  72. @Override
  73. public void onClick(DialogInterface dialog, int which) {
  74. dialog.dismiss();
  75. }
  76. });
  77. dialog = builder.create();
  78. dialog.show();
  79. return true;
  80. }
  81. });
  82. }
  83. private void showQueryData(){
  84. if (list!=null){
  85. list.clear();
  86. }
  87. //从数据库中查询数据(保存的标签)
  88. list = mSQLiteHelper.query();
  89. adapter = new NotepadAdapter(this, list);
  90. listView.setAdapter(adapter);
  91. }
  92. @Override
  93. protected void onActivityResult(int requestCode,int resultCode, Intent data){
  94. super.onActivityResult(requestCode, resultCode, data);
  95. if (requestCode==1&&resultCode==2){
  96. showQueryData();
  97. }
  98. }
  99. }

七、搭建添加记录界面和修改记录界面的布局activity_record.xml

当点击记事本界面的“添加”按钮时,会跳转到添加记录界面,当点击记事本界面列表中的item时,会跳转到修改记录界面。由于这两个界面上的控件与功能基本相同,因此设置同一个Activity和同一个布局文件显示。

1.选中cn.itcast.notepad包,右击-【New】-【Activity】,命名为RecordActivity

2.activity_record.xml代码如下

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:background="#fefefe">
  7. <RelativeLayout
  8. android:layout_width="match_parent"
  9. android:layout_height="45dp"
  10. android:background="#fb7a6a"
  11. android:orientation="horizontal">
  12. <ImageView
  13. android:id="@+id/note_back"
  14. android:layout_width="45dp"
  15. android:layout_height="wrap_content"
  16. android:layout_centerVertical="true"
  17. android:paddingLeft="11dp"
  18. android:src="@drawable/back" />
  19. <TextView
  20. android:id="@+id/note_name"
  21. android:layout_width="wrap_content"
  22. android:layout_height="wrap_content"
  23. android:layout_centerInParent="true"
  24. android:gravity="center"
  25. android:text="记事本"
  26. android:textColor="@android:color/white"
  27. android:textSize="15sp"
  28. android:textStyle="bold" />
  29. </RelativeLayout>
  30. <TextView
  31. android:id="@+id/tv_time"
  32. android:layout_width="match_parent"
  33. android:layout_height="wrap_content"
  34. android:textSize="15sp"
  35. android:paddingTop="10dp"
  36. android:paddingBottom="10dp"
  37. android:gravity="center"
  38. android:visibility="gone"
  39. android:textColor="#fb7a6a"/>
  40. <EditText
  41. android:id="@+id/note_content"
  42. android:layout_width="match_parent"
  43. android:layout_height="match_parent"
  44. android:layout_weight="1"
  45. android:gravity="top"
  46. android:hint="请输入要添加的内容"
  47. android:paddingLeft="5dp"
  48. android:textColor="@android:color/black"
  49. android:background="#fefefe" />
  50. <View
  51. android:layout_width="match_parent"
  52. android:layout_height="1dp"
  53. android:background="#fb7a6a"/>
  54. <LinearLayout
  55. android:layout_width="match_parent"
  56. android:layout_height="55dp"
  57. android:orientation="horizontal">
  58. <ImageView
  59. android:id="@+id/delete"
  60. android:layout_width="0dp"
  61. android:layout_weight="1"
  62. android:layout_height="wrap_content"
  63. android:src="@drawable/delete"
  64. android:paddingBottom="15dp"
  65. android:paddingTop="9dp"/>
  66. <ImageView
  67. android:id="@+id/note_save"
  68. android:layout_width="0dp"
  69. android:layout_weight="1"
  70. android:layout_height="wrap_content"
  71. android:src="@drawable/save_note"
  72. android:paddingBottom="15dp"
  73. android:paddingTop="9dp"/>
  74. </LinearLayout>
  75. </LinearLayout>

八、实现添加记录界面的功能RecordActivity.java

1.包括编辑记录、保存记录、清除记录功能

2.步骤

初始化界面控件,设置点击事件。

switch通过id判断被点击的按钮属于哪个控件。
当选择“保存”按钮时,首先要获取输入框中的内容getText(),将文本信息转换为字符串toString(),再将空字符串清除掉trim()。
接着判断输入的内容是否>0,如果大于0,调用insertData()方法,将记录添加到数据库中,需传入两个参数,一个是输入的内容,一个点击保存按钮的时间。
接下来判断数据是否保存成功,如果成功,要弹出一个“保存成功”的提示。失败,要弹出一个“保存失败”的提示。所以需要创建一个showToast()方法。保存成功还要调用setResult()方法返回一个返回码:2。

showToast()方法用于显示一些信息,在这个方法中调用makeText()方法。

创建initData()方法,创建数据库。

initData()方法在onCreat()方法中调用一下。

3.具体代码RecordActivity.java

  1. package cn.itcast.notepad;
  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.view.View;
  6. import android.widget.EditText;
  7. import android.widget.ImageView;
  8. import android.widget.TextView;
  9. import android.widget.Toast;
  10. import cn.itcast.notepad.database.SQLiteHelper;
  11. import cn.itcast.notepad.utils.DBUtils;
  12. public class RecordActivity extends Activity implements View.OnClickListener {
  13. ImageView note_back;
  14. TextView note_time;
  15. EditText content;
  16. ImageView delete;
  17. ImageView note_save;
  18. SQLiteHelper mSQLiteHelper;
  19. TextView noteName;
  20. String id;
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_record);
  25. note_back = (ImageView) findViewById(R.id.note_back);
  26. note_time = (TextView)findViewById(R.id.tv_time);
  27. content = (EditText) findViewById(R.id.note_content);
  28. delete = (ImageView) findViewById(R.id.delete);
  29. note_save = (ImageView) findViewById(R.id.note_save);
  30. noteName = (TextView) findViewById(R.id.note_name);
  31. note_back.setOnClickListener(this);
  32. delete.setOnClickListener(this);
  33. note_save.setOnClickListener(this);
  34. initData();
  35. }
  36. protected void initData() {
  37. mSQLiteHelper = new SQLiteHelper(this);
  38. noteName.setText("添加记录");
  39. Intent intent = getIntent();
  40. if(intent!= null){
  41. id = intent.getStringExtra("id");
  42. if (id != null){
  43. noteName.setText("修改记录");
  44. content.setText(intent.getStringExtra("content"));
  45. note_time.setText(intent.getStringExtra("time"));
  46. note_time.setVisibility(View.VISIBLE);
  47. }
  48. }
  49. }
  50. @Override
  51. public void onClick(View v) {
  52. switch (v.getId()) {
  53. case R.id.note_back:
  54. finish();
  55. break;
  56. case R.id.delete:
  57. content.setText("");
  58. break;
  59. case R.id.note_save:
  60. String noteContent=content.getText().toString().trim();
  61. if (id != null){//修改操作
  62. if (noteContent.length()>0){
  63. if (mSQLiteHelper.updateData(id, noteContent, DBUtils.getTime())){
  64. showToast("修改成功");
  65. setResult(2);
  66. finish();
  67. }else {
  68. showToast("修改失败");
  69. }
  70. }else {
  71. showToast("修改内容不能为空!");
  72. }
  73. }else {
  74. //向数据库中添加数据
  75. if (noteContent.length()>0){
  76. if (mSQLiteHelper.insertData(noteContent, DBUtils.getTime())){
  77. showToast("保存成功");
  78. setResult(2);
  79. finish();
  80. }else {
  81. showToast("保存失败");
  82. }
  83. }else {
  84. showToast("修改内容不能为空!");
  85. }
  86. }
  87. break;
  88. }
  89. }
  90. public void showToast(String message){
  91. Toast.makeText(RecordActivity.this,message,Toast.LENGTH_SHORT).show();
  92. }
  93. }

九、实现修改记录界面的功能

(备注:前面代码已经包含此内容,这里弄清楚就好)

比添加记录界面多了查看记录和修改记录的功能。

1.实现查看记录功能。

(1)记事本界面列表的每个Item只显示2行记录信息,如果想要查看更多的记录内容,则需要点击Item,进入修改记录界面进行查看。

(2)在NotepadActivity的initDate()方法中,添加跳转到修改记录界面的代码。
通过setOnItemClickListener()方法实现Item的点击事件,点击Item,会调用onItemClick()方法,在该方法中首先通过get()方法获取对应的Item数据。创建intent对象,需要传入两个参数,一个是上下文信息,另一个是需要跳转的activity的名称。接着将这些数据通过putExtra()方法封装到intent对象中,最后调用startActivityForResult()方法跳转到修改记录界面,请求码设为1。

  1. protected void initData() {
  2. ...
  3. listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  4. @Override
  5. public void onItemClick(AdapterView<?> parent,View view,int position,long id){
  6. NotepadBean notepadBean = list.get(position);
  7. Intent intent = new Intent(NotepadActivity.this, RecordActivity.class);
  8. intent.putExtra("id", notepadBean.getId());
  9. intent.putExtra("time", notepadBean.getNotepadTime()); //记录的时间
  10. intent.putExtra("content", notepadBean.getNotepadContent()); //记录的内容
  11. NotepadActivity.this.startActivityForResult(intent, 1);
  12. }
  13. });

(3)在RecordActivity中找到initData()方法,在该方法中接收记事本界面传递过来的记录数据并显示到界面上。
首先获取intent对象,接着判断对象是否为空。如果不为空,获取传递的数据。
先获取id ,判断id是否为空,如果不为空,需要将标题设为“修改记录”。然后通过get分别获取记录时间、记录内容并通过set显示,最后将记录时间设置为显示状态。

  1. protected void initData() {
  2. mSQLiteHelper = new SQLiteHelper(this);
  3. noteName.setText("添加记录");
  4. Intent intent = getIntent();
  5. if(intent!= null){
  6. id = intent.getStringExtra("id");
  7. if (id != null){
  8. noteName.setText("修改记录");
  9. content.setText(intent.getStringExtra("content"));
  10. note_time.setText(intent.getStringExtra("time"));
  11. note_time.setVisibility(View.VISIBLE);
  12. }
  13. }
  14. }

2.实现修改记录功能

(1)在RecordActivity的onClick()方法中,找到“保存”按钮的点击事件,在该事件中,判断传递过来的id是否为空,如果不为空,那就是修改记录功能。将修改记录的id、修改的内容、保存修改记录的时间传递到updateData()方法中,进行修改。
如果为空,就是添加记录功能。

(2)具体代码:

  1. public void onClick(View v) {
  2. switch (v.getId()) {
  3. ...
  4. case R.id.note_save:
  5. String noteContent=content.getText().toString().trim();
  6. if (id != null){//修改操作
  7. if (noteContent.length()>0){
  8. if (mSQLiteHelper.updateData(id, noteContent, DBUtils.getTime())){
  9. showToast("修改成功");
  10. setResult(2);
  11. finish();
  12. }else {
  13. showToast("修改失败");
  14. }
  15. }else {
  16. showToast("修改内容不能为空!");
  17. }
  18. }else {
  19. ...
  20. }
  21. }

十、删除记事本中的记录

(备注:前面代码已经包含此内容,这里弄清楚就好)

(1)当长按列表的Item,此时会弹出一个对话框提示是否删除记录,因此在NotepadActivity的initData()方法中要加上删除记录的代码。

(2)首先,通过setOnItemLongClickListener()设置长按事件的监听器。当长按Item,会调用onItemLongClick()方法,在该方法中实现长按事件。
创建一个AlertDialog对话框,用于提示用户是否删除。创建Builder对象,在这个对象中传入上下文信息。

(3)NotepadActivity的initData()方法代码:

  1. listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
  2. @Override
  3. public boolean onItemLongClick(AdapterView<?> parent, View view, final int
  4. position, long id) {
  5. AlertDialog dialog;
  6. AlertDialog.Builder builder = new AlertDialog.Builder( NotepadActivity.this)
  7. .setMessage("是否删除此事件?")
  8. .setPositiveButton("确定", new DialogInterface.OnClickListener() {
  9. @Override
  10. public void onClick(DialogInterface dialog, int which) {
  11. NotepadBean notepadBean = list.get(position);
  12. if(mSQLiteHelper.deleteData(notepadBean.getId())){
  13. list.remove(position);
  14. adapter.notifyDataSetChanged();
  15. Toast.makeText(NotepadActivity.this,"删除成功",
  16. Toast.LENGTH_SHORT).show();
  17. }
  18. }
  19. })
  20. .setNegativeButton("取消", new DialogInterface.OnClickListener() {
  21. @Override
  22. public void onClick(DialogInterface dialog, int which) {
  23. dialog.dismiss();
  24. }
  25. });
  26. dialog = builder.create();
  27. dialog.show();
  28. return true;
  29. }
  30. });

本文转载自: https://blog.csdn.net/weixin_72634509/article/details/127634062
版权归原作者 Slowfish172 所有, 如有侵权,请联系我们删除。

“Android——记事本功能业务(完整代码)”的评论:

还没有评论