您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關android如何實現記事本app,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
自己寫的一個簡單的記事本app,效果如下:
一、首先是第一個界面的編寫,最上面是一個TextView,中間是一個Linearlayout中嵌套一個listview布局,最下面是一個button。下面附上第一個頁面的簡單布局xml文件。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/darker_gray" android:orientation="vertical" > <TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="記事本列表" android:textSize="20sp" android:paddingTop="10dp" android:paddingBottom="5dp" android:background="#039DCF" android:gravity="center"/> <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" > <ListView android:id="@+id/listview" android:layout_margin="5dp" android:background="#81966F" android:layout_width="match_parent" android:layout_height="wrap_content" > </ListView> </LinearLayout> <Button android:id="@+id/btn_editnote" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/btn_selctor" android:layout_gravity="center" android:layout_marginBottom="10dp" android:text="添加備忘錄" android:textSize="20sp" /> </LinearLayout>
至于button的樣式btn_selector就是自己定義的button樣式。
二、其次就是設置ListView中數據顯示的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_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:singleLine="true" android:text="Large Text" android:textAppearance="?android:attr/textAppearanceLarge" /> <TextView android:id="@+id/tv_date" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:text="TextView" /> </LinearLayout>
三、編寫第二個界面樣式,第二個界面是最上面一個linearlayout,里面包含兩個button和一個TextView。代碼如下:
<?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="#FFAE99" android:orientation="vertical" > <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <Button android:id="@+id/btn_cancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/btn_selctor" android:text="取消" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="編輯備忘錄" android:textSize="20sp" /> <TextView android:id="@+id/tv_date" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="" /> </LinearLayout> <Button android:id="@+id/btn_ok" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/btn_selctor" android:text="保存" /> </LinearLayout> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:scrollbars="vertical" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_marginLeft="2dp" android:orientation="vertical" > <EditText android:id="@+id/et_content" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#FFAE99" android:textSize="20sp" /> </LinearLayout> </ScrollView> </LinearLayout>
四、將日志的數據保存在數據庫中,使用sqlite來創建數據庫,數據庫中有三個屬性,"_id"、"content"、"date"這三個屬性,創建一個NoteDB來創建數據庫。
package com.example.datenote; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class NotesDB extends SQLiteOpenHelper { public static final String TABLE_NAME_NOTES = "note"; public static final String COLUMN_NAME_ID = "_id"; public static final String COLUMN_NAME_NOTE_CONTENT = "content"; public static final String COLUMN_NAME_NOTE_DATE = "date"; public NotesDB(Context context) { super(context, "note", null, 1); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE " + TABLE_NAME_NOTES + "(" + COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME_NOTE_CONTENT + " TEXT NOT NULL DEFAULT\"\"," + COLUMN_NAME_NOTE_DATE + " TEXT NOT NULL DEFAULT\"\"" + ")"; Log.d("SQL", sql); db.execSQL(sql); // String sql1="insert into "+TABLE_NAME_NOTES+"values("+"1,"+"'寫作業',"+"'晚上要寫作業的干活'"+")"; // Log.d("SQL1", sql1); // db.execSQL(sql1); // ContentValues values=new ContentValues(); // values.put("id",1); // values.put("content","寫作業"); // values.put("date", "2013-1-2"); // db.insert("note", null, values); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } }
五、實現點擊添加事件的跳轉,在第一個頁面中點擊添加備忘錄后會跳轉到第二個界面,設置點擊事件,由一個activity跳轉到另外一個activity,我使用的是intent方式。另外,在ListView中點擊每個已記錄下來的日志也會跳轉到第二個界面,只是顯示的不是空白的EditText,而是包含日志的EditText。MainActivity如下:
package com.example.datenote; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnScrollListener, OnItemClickListener, OnItemLongClickListener { private Context mContext; private ListView listview; private SimpleAdapter simp_adapter; private List<Map<String, Object>> dataList; private Button addNote; private TextView tv_content; private NotesDB DB; private SQLiteDatabase dbread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); tv_content = (TextView) findViewById(R.id.tv_content); listview = (ListView) findViewById(R.id.listview); dataList = new ArrayList<Map<String, Object>>(); addNote = (Button) findViewById(R.id.btn_editnote); mContext = this; addNote.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { noteEdit.ENTER_STATE = 0; Intent intent = new Intent(mContext, noteEdit.class); Bundle bundle = new Bundle(); bundle.putString("info", ""); intent.putExtras(bundle); startActivityForResult(intent, 1); } }); DB = new NotesDB(this); dbread = DB.getReadableDatabase(); // 清空數據庫中表的內容 //dbread.execSQL("delete from note"); RefreshNotesList(); listview.setOnItemClickListener(this); listview.setOnItemLongClickListener(this); listview.setOnScrollListener(this); } public void RefreshNotesList() { int size = dataList.size(); if (size > 0) { dataList.removeAll(dataList); simp_adapter.notifyDataSetChanged(); listview.setAdapter(simp_adapter); } simp_adapter = new SimpleAdapter(this, getData(), R.layout.item, new String[] { "tv_content", "tv_date" }, new int[] { R.id.tv_content, R.id.tv_date }); listview.setAdapter(simp_adapter); } private List<Map<String, Object>> getData() { Cursor cursor = dbread.query("note", null, "content!=\"\"", null, null, null, null); while (cursor.moveToNext()) { String name = cursor.getString(cursor.getColumnIndex("content")); String date = cursor.getString(cursor.getColumnIndex("date")); Map<String, Object> map = new HashMap<String, Object>(); map.put("tv_content", name); map.put("tv_date", date); dataList.add(map); } cursor.close(); return dataList; } @Override public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } // 滑動listview監聽事件 @Override public void onScrollStateChanged(AbsListView arg0, int arg1) { // TODO Auto-generated method stub switch (arg1) { case SCROLL_STATE_FLING: Log.i("main", "用戶在手指離開屏幕之前,由于用力的滑了一下,視圖能依靠慣性繼續滑動"); case SCROLL_STATE_IDLE: Log.i("main", "視圖已經停止滑動"); case SCROLL_STATE_TOUCH_SCROLL: Log.i("main", "手指沒有離開屏幕,試圖正在滑動"); } } // 點擊listview中某一項的監聽事件 @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { noteEdit.ENTER_STATE = 1; // Log.d("arg2", arg2 + ""); // TextView // content=(TextView)listview.getChildAt(arg2).findViewById(R.id.tv_content); // String content1=content.toString(); String content = listview.getItemAtPosition(arg2) + ""; String content1 = content.substring(content.indexOf("=") + 1, content.indexOf(",")); Log.d("CONTENT", content1); Cursor c = dbread.query("note", null, "content=" + "'" + content1 + "'", null, null, null, null); while (c.moveToNext()) { String No = c.getString(c.getColumnIndex("_id")); Log.d("TEXT", No); // Intent intent = new Intent(mContext, noteEdit.class); // intent.putExtra("data", text); // setResult(4, intent); // // intent.putExtra("data",text); // startActivityForResult(intent, 3); Intent myIntent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("info", content1); noteEdit.id = Integer.parseInt(No); myIntent.putExtras(bundle); myIntent.setClass(MainActivity.this, noteEdit.class); startActivityForResult(myIntent, 1); } } @Override // 接受上一個頁面返回的數據,并刷新頁面 protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1 && resultCode == 2) { RefreshNotesList(); } } // 點擊listview中某一項長時間的點擊事件 @Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { final int n=arg2; Builder builder = new AlertDialog.Builder(this); builder.setTitle("刪除該日志"); builder.setMessage("確認刪除嗎?"); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String content = listview.getItemAtPosition(n) + ""; String content1 = content.substring(content.indexOf("=") + 1, content.indexOf(",")); Cursor c = dbread.query("note", null, "content=" + "'" + content1 + "'", null, null, null, null); while (c.moveToNext()) { String id = c.getString(c.getColumnIndex("_id")); String sql_del = "update note set content='' where _id=" + id; dbread.execSQL(sql_del); RefreshNotesList(); } } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create(); builder.show(); return true; } }
六、編寫第二個跳轉后界面的Activity,如下:
package com.example.datenote; import java.text.SimpleDateFormat; import java.util.Date; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class noteEdit extends Activity { private TextView tv_date; private EditText et_content; private Button btn_ok; private Button btn_cancel; private NotesDB DB; private SQLiteDatabase dbread; public static int ENTER_STATE = 0; public static String last_content; public static int id; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); // 設置無標題 requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.edit); tv_date = (TextView) findViewById(R.id.tv_date); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String dateString = sdf.format(date); tv_date.setText(dateString); et_content = (EditText) findViewById(R.id.et_content); // 設置軟鍵盤自動彈出 getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); DB = new NotesDB(this); dbread = DB.getReadableDatabase(); Bundle myBundle = this.getIntent().getExtras(); last_content = myBundle.getString("info"); Log.d("LAST_CONTENT", last_content); et_content.setText(last_content); // 確認按鈕的點擊事件 btn_ok = (Button) findViewById(R.id.btn_ok); btn_ok.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { // 獲取日志內容 String content = et_content.getText().toString(); Log.d("LOG1", content); // 獲取寫日志時間 Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String dateNum = sdf.format(date); String sql; String sql_count = "SELECT COUNT(*) FROM note"; SQLiteStatement statement = dbread.compileStatement(sql_count); long count = statement.simpleQueryForLong(); Log.d("COUNT", count + ""); Log.d("ENTER_STATE", ENTER_STATE + ""); // 添加一個新的日志 if (ENTER_STATE == 0) { if (!content.equals("")) { sql = "insert into " + NotesDB.TABLE_NAME_NOTES + " values(" + count + "," + "'" + content + "'" + "," + "'" + dateNum + "')"; Log.d("LOG", sql); dbread.execSQL(sql); } } // 查看并修改一個已有的日志 else { Log.d("執行命令", "執行了該函數"); String updatesql = "update note set content='" + content + "' where _id=" + id; dbread.execSQL(updatesql); // et_content.setText(last_content); } Intent data = new Intent(); setResult(2, data); finish(); } }); btn_cancel = (Button) findViewById(R.id.btn_cancel); btn_cancel.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { finish(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); // if (requestCode == 3 && resultCode == 4) { // last_content=data.getStringExtra("data"); // Log.d("LAST_STRAING", last_content+"gvg"); // } } }
七、其中,對ListView添加OnItemLongclicklistener,長點擊之后會彈出一個dialog對話框提醒要不要刪除該日志文件。
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { final int n=arg2; Builder builder = new AlertDialog.Builder(this); builder.setTitle("刪除該日志"); builder.setMessage("確認刪除嗎?"); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String content = listview.getItemAtPosition(n) + ""; String content1 = content.substring(content.indexOf("=") + 1, content.indexOf(",")); Cursor c = dbread.query("note", null, "content=" + "'" + content1 + "'", null, null, null, null); while (c.moveToNext()) { String id = c.getString(c.getColumnIndex("_id")); String sql_del = "update note set content='' where _id=" + id; dbread.execSQL(sql_del); RefreshNotesList(); } } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); builder.create(); builder.show(); return true; }
注意最后將返回值設為true,否則會和OnItemClickListener產生沖突。
附上長點擊刪除的效果。
關于“android如何實現記事本app”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,使各位可以學到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。