1. Trang chủ
  2. » Công Nghệ Thông Tin

Lập trình Android: Tạo NotePad docx

19 334 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 19
Dung lượng 211,5 KB

Nội dung

Tạo NotePad Hẳn các bạn đã quen với ứng dụng NotePad trên Window.. Sau đây mình sẽ demo cách tạo 1 ứng dụng NotePad với vài chức năng chỉnh sửa văn bản trên hệ điều hành Android : 1/ Các

Trang 1

Tạo NotePad Hẳn các bạn đã quen với ứng dụng NotePad trên Window Sau đây mình sẽ demo cách tạo 1 ứng dụng NotePad với vài chức năng chỉnh sửa văn bản trên hệ điều hành

Android :

1/ Các bạo tạo Project như sau:

Project name: MyNoteEditer

Build Target: Android 2.1

Application name: MyNoteEditer

Package name: com.app.MyNoteEditer

Create Activity: OpenNotes

2/ Các bạn tạo file new_text.xml trong folder layout như sau:

<?xml version ="1.0" encoding ="utf-8" ?>

<LinearLayout

xmlns:android ="http://schemas.android.com/apk/res/android"

android:orientation ="vertical"

android:layout_width ="fill_parent"

android:layout_height ="fill_parent" >

<LinearLayout android:orientation ="horizontal" android:layout_width ="fill_parent"

android:layout_height ="wrap_content" >

<TextView android:layout_width ="wrap_content"

android:layout_height ="wrap_content" android:text ="Title" />

<EditText android:id ="@+id/title"

android:layout_width ="wrap_content" android:layout_height ="wrap_content"

android:layout_weight ="1" />

</LinearLayout>

<TextView android:layout_width ="wrap_content"

android:layout_height ="wrap_content" android:text ="Body Text" />

<EditText android:id ="@+id/insertdata" android:layout_width ="fill_parent" android:layout_height ="wrap_content" android:layout_weight ="1"

android:scrollbars ="vertical" />

<LinearLayout android:orientation ="horizontal"

android:layout_width ="fill_parent" android:layout_height ="wrap_content" >

<Button android:id ="@+id/save" android:text ="Save"

android:layout_width ="wrap_content" android:layout_height ="wrap_content" />

<Button android:text ="Cut" android:id ="@+id/cut"

android:layout_width ="wrap_content" android:layout_height ="wrap_content" />

<Button android:text ="Copy" android:id ="@+id/copy"

android:layout_width ="wrap_content" android:layout_height ="wrap_content" />

<Button android:text ="Paste" android:id ="@+id/paste"

android:layout_width ="wrap_content" android:layout_height ="wrap_content" />

<Button android:text ="Back" android:id ="@+id/back"

android:layout_width ="wrap_content" android:layout_height ="wrap_content" />

Trang 2

</LinearLayout>

</LinearLayout>

3/ Các bạn tạo file notes_list.xm trong folder layout như sau:

<?xml version ="1.0" encoding ="UTF-8" ?>

<LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android"

android:layout_width ="wrap_content"

android:layout_height ="wrap_content" >

<ListView android:id ="@+id/android:list"

android:layout_width ="wrap_content"

android:layout_height ="wrap_content" />

<TextView android:id ="@+id/android:empty"

android:layout_width ="wrap_content"

android:layout_height ="wrap_content"

android:text ="No Notes…" />

</LinearLayout>

4/ Các bạn tạo tiếp file notes_row.xml trên folder layout như sau:

<?xml version ="1.0" encoding ="UTF-8" ?>

<TextView android:id ="@+id/text1"

xmlns:android ="http://schemas.android.com/apk/res/android"

android:layout_width ="wrap_content"

android:layout_height ="wrap_content" />

5/ Các bạn chỉnh code file main.xml như sau:

<?xml version ="1.0" encoding ="utf-8" ?>

<LinearLayout xmlns:android ="http://schemas.android.com/apk/res/android" android:layout_width ="wrap_content"

android:layout_height ="wrap_content" >

<ListView android:id ="@+id/android:list"

android:layout_width ="wrap_content"

android:layout_height ="wrap_content" />

<TextView android:id ="@+id/android:empty"

android:layout_width ="wrap_content"

android:layout_height ="wrap_content"

android:text ="No New Notes…Press on Menu to Add New Note" />

</LinearLayout>

6/ Các bạn tạo file NewText.java trong package và thêm code :

package com.app.MyNoteEditer;

import android.app.Activity;

Trang 3

import android.content.Intent;

import android.os.Bundle;

import android.text.Editable;

import android.text.Spannable;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

public class NewText extends Activity implements OnClickListener {

EditText editbox1;

EditText editbox2;

Button cutb;

Button copyb;

Button pasteb;

Button saveb,backb;

Editable s1,s2;

Spannable str;

Spannable str2;

private Long mRowId;

public void onCreate(Bundle icicle) {

super.onCreate(icicle);

Trang 4

setContentView(R.layout.new_text);

editbox1 =(EditText) findViewById(R.id.title);

editbox2 =(EditText) findViewById(R.id.insertdata);

mRowId = null;

Bundle extras = getIntent().getExtras();

if (extras != null) {

String title = extras.getString(NotesDbAdapter.KEY_TITLE); String body = extras.getString(NotesDbAdapter.KEY_BODY); mRowId = extras.getLong(NotesDbAdapter.KEY_ROWID);

if (title != null) {

editbox1.setText(title);

}

if (body != null) {

editbox2.setText(body);

}

}

cutb =(Button) findViewById(R.id.cut);

cutb.setOnClickListener(this);

copyb =(Button)findViewById(R.id.copy);

copyb.setOnClickListener(this);

pasteb =(Button)findViewById(R.id.paste);

pasteb.setOnClickListener(this);

saveb =(Button) findViewById(R.id.save);

saveb.setOnClickListener(this);

Trang 5

backb =(Button) findViewById(R.id.back);

backb.setOnClickListener(this);

}

public void onBackPressed() {

moveTaskToBack(true);

return;

}

@Override

public void onClick(View v) {

// TODO Auto-generated method stub

switch(v.getId())

{

case R.id.save :

Bundle bundle = new Bundle();

bundle.putString(NotesDbAdapter.KEY_TITLE,

editbox1.getText().toString());

bundle.putString(NotesDbAdapter.KEY_BODY,

editbox2.getText().toString());

if (mRowId != null) {

bundle.putLong(NotesDbAdapter.KEY_ROWID, mRowId); }

Intent mIntent = new Intent();

mIntent.putExtras(bundle);

setResult(RESULT_OK, mIntent);

Trang 6

finish();

break;

case R.id.copy :

//String selectedText =

editbox2.getText().substring(editbox2.getSelectionStart(), editbox2.getSelectionEnd());

if(editbox2.getSelectionEnd() > editbox2.getSelectionStart())

{

s1 = (Editable)

editbox2.getText().subSequence(editbox2.getSelectionStart(),

editbox2.getSelectionEnd());

}else

{

s1 = (Editable)

editbox2.getText().subSequence(editbox2.getSelectionEnd(),

editbox2.getSelectionStart());

}

break;

case R.id.cut :

if(editbox2.getSelectionEnd() > editbox2.getSelectionStart())

{

s1 = (Editable)

editbox2.getText().subSequence(editbox2.getSelectionStart(),

editbox2.getSelectionEnd());

}else

{

Trang 7

s1 = (Editable)

editbox2.getText().subSequence(editbox2.getSelectionEnd(),

editbox2.getSelectionStart());

}

editbox2.getText().replace(Math.min(editbox2.getSelectionStart(), editbox2.getSelectionEnd()), Math.max(editbox2.getSelectionStart(),

editbox2.getSelectionEnd()),"", 0, 0);

break;

case R.id.paste :

editbox2.getText().replace(Math.min(editbox2.getSelectionStart(),

editbox2.getSelectionEnd()), Math.max(editbox2.getSelectionStart(),

editbox2.getSelectionEnd()),s1, 0, s1.length());

break;

case R.id.back :

Intent mIntent2 = new Intent(this,OpenNotes.class);

startActivity(mIntent2);

finish();

break;

}

}

}

7/ Các bạo tạo file NotesDbAdapter.java trong package để làm chức năng lưu các Note bạn đã tạo ra:

package com.app.MyNoteEditer;

Trang 8

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.SQLException;

import android.database.sqlite.SQLiteDatabase;

import android.database.sqlite.SQLiteOpenHelper;

import android.util.Log;

public class NotesDbAdapter {

public static final String KEY_TITLE = "title";

public static final String KEY_BODY = "body";

public static final String KEY_ROWID = "_id";

private static final String TAG = "NotesDbAdapter";

private DatabaseHelper mDbHelper;

private SQLiteDatabase mDb;

private static final String DATABASE_CREATE = "create table notes (_id integer primary key autoincrement, " + "title text not null, body text not null);";

private static final String DATABASE_NAME = "data";

private static final String DATABASE_TABLE = "notes";

private static final int DATABASE_VERSION = 2;

Trang 9

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper {

DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION); }

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL(DATABASE_CREATE);

}

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");

db.execSQL("DROP TABLE IF EXISTS notes");

onCreate(db);

}

}

public NotesDbAdapter(Context ctx) {

this.mCtx = ctx;

Trang 10

}

public NotesDbAdapter open() throws SQLException {

mDbHelper = new DatabaseHelper(mCtx);

mDb = mDbHelper.getWritableDatabase();

return this;

}

public void close() {

mDbHelper.close();

}

public long createNote(String title, String body) {

ContentValues initialValues = new ContentValues();

initialValues.put(KEY_TITLE, title);

initialValues.put(KEY_BODY, body);

return mDb.insert(DATABASE_TABLE, null, initialValues);

}

public boolean deleteNote(long rowId) {

return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; }

public void deleteAllNote() {

Trang 11

mDb.delete(DATABASE_TABLE, null, null);

}

public Cursor fetchAllNotes() {

return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY}, null, null, null, null, null);

}

public Cursor fetchNote(long rowId) throws SQLException {

Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[]

{KEY_ROWID, KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null, null, null, null, null);

if (mCursor != null) {

mCursor.moveToFirst();

}

return mCursor;

}

public boolean updateNote(long rowId, String title, String body) {

ContentValues args = new ContentValues();

args.put(KEY_TITLE, title);

args.put(KEY_BODY, body);

return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;

}

}

Trang 12

8/ Tiếp theo các bạn chỉnh code trong file chính OpenNotes.java nhu sau:

package com.app.MyNoteEditer;

import android.app.ListActivity;

import android.content.Intent;

import android.database.Cursor;

import android.os.Bundle;

import android.view.ContextMenu;

import android.view.Menu;

import android.view.MenuItem;

import android.view.View;

import android.view.ContextMenu.ContextMenuInfo;

import android.widget.ListView;

import android.widget.SimpleCursorAdapter;

import android.widget.AdapterView.AdapterContextMenuInfo;

public class OpenNotes extends ListActivity {

private static final int ACTIVITY_CREATE=0;

private static final int ACTIVITY_EDIT=1;

private static final int INSERT_ID = Menu.FIRST;

private static final int DELETE_ID = Menu.FIRST + 1;

Trang 13

private NotesDbAdapter mDbHelper;

private Cursor mNotesCursor;

/** Called when the activity is first created */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

mDbHelper = new NotesDbAdapter(this);

mDbHelper.open();

fillData();

}

public void onBackPressed() {

moveTaskToBack(true);

this.finish();

return;

}

private void fillData() {

// Get all of the rows from the database and create the item list

mNotesCursor = mDbHelper.fetchAllNotes();

startManagingCursor(mNotesCursor);

// Create an array to specify the fields we want to display in the list (only TITLE) String[] from = new String[]{NotesDbAdapter.KEY_TITLE};

Trang 14

// and an array of the fields we want to bind those fields to (in this case just text1) int[] to = new int[]{R.id.text1};

// Now create a simple cursor adapter and set it to display

SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.notes_row, mNotesCursor, from, to);

setListAdapter(notes);

}

public boolean onCreateOptionsMenu(Menu menu) {

super.onCreateOptionsMenu(menu);

menu.add(0, INSERT_ID, 0, "New Note");

return true;

}

public boolean onMenuItemSelected(int featureId, MenuItem item) {

switch(item.getItemId()) {

case INSERT_ID:

createNote();

return true;

}

return super.onMenuItemSelected(featureId, item);

}

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {

super.onCreateContextMenu(menu, v, menuInfo);

menu.add(0, DELETE_ID, 0, "Delete");

Trang 15

}

public boolean onContextItemSelected(MenuItem item) {

switch(item.getItemId()) {

case DELETE_ID:

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

mDbHelper.deleteNote(info.id);

fillData();

return true;

}

return super.onContextItemSelected(item);

}

private void createNote() {

Intent i = new Intent(this, NewText.class);

startActivityForResult(i, ACTIVITY_CREATE);

}

protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id);

Cursor c = mNotesCursor;

c.moveToPosition(position);

Intent i = new Intent(this, NewText.class);

i.putExtra(NotesDbAdapter.KEY_ROWID, id);

i.putExtra(NotesDbAdapter.KEY_TITLE,

c.getString(c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));

Ngày đăng: 07/08/2014, 14:20

TỪ KHÓA LIÊN QUAN

w