安卓记事本程序源代码

合集下载

Android记事本

Android记事本

1.只是在主程序里面添加此代码:TextView textView = new TextView(this);textView.setText("你好啊");setContentView(textView);就会在Android虚拟机上显示“你好啊”2.只在Main.xml里面添加代码:<TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:text="你好"/>3.4.设置超链接:android:autoLink=”all”5.跑马灯:android:singleLine=”true”把所以要跑马灯的都显示成一行android:focusable="true"android:ellipsize="marquee"android:marqueeRepeatLimit="marquee_forever"android:focusableInTouchMode="true"6.设置字体颜色:TextView tv = (TextView) findViewById();String str = "欢迎大家收看《Android开发从零开始》系列课程,感谢大家的支持。

";SpannableStringBuilder style = new SpannableStringBuilder(str); style.setSpan(new ForegroundColorSpan(Color.RED), 0, 6,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);style.setSpan(new ForegroundColorSpan(Color.GREEN), 6, 21,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);style.setSpan(new ForegroundColorSpan(Color.BLUE), 21, 26,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);tv.setText(style);7.8.@动画,是android 自带的an1.setDuration(1000);休息的时间问1000毫秒imgv1.startAnimation(an1);// startAnimation 启动动画9.给自己的界面设置空间大小Android:layout_weight=”X”10.实现图片的循环a先取得getContext的返回最大值Public int getContext(){Return Integer.MAX_VALUE;}b有就是设置图片给ImageView对象Imageview.setImageResource(resides[position%resIds.length]);c.我们还可以给图片添加一个边框首先定义一个int mGalleryItemBackground;,然后取得Gallery属性的Index id的值public ImageAdapter(Context c) {mContext = c;// 使用在res/value/attrs.xml中的Gallery属性TypedArray a = obtainStyledAttributes(R.styleable.Gallery);// 取得Gallery属性的Index idmGalleryItemBackground = a.getResourceId(R.styleable.Gallery_android_galleryItemBackground, 0);// 让对象的styleable属性能够反复使用a.recycle();}在res/value/attrs.xml的代码<declare-styleable name="Gallery"><attr name="android:galleryItemBackground"/></declare-styleable>11.AlertDialog的使用AlertDialog.Builder builder = new AlertDialog.Builder(C018_onDoubleClickActivity.this);builder.setTitle("双击");builder.setMessage("Very Good");builder.show();图片的淡进淡出:AlphaAnimationaa = new AlphaAnimation(1, 0);// 1, 0从透明到不透明图片的移动:TranslateAnimationta = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF, 0.5f);ta.setDuration(3000); //显示的时间startAnimation(al);//启动startAnimation(ta);图片的旋转:RotateAnimationra = new RotateAnimation(0, 720, Animation.RELATIVE_TO_PARENT, 0.5f, Animation.RELATIVE_TO_PARENT, 0.5f);图片的伸缩:ScaleAnimationsa = new ScaleAnimation(0, 1, 0, 1, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);帧动画Alpha渐变效果共同属性fromX, toX, fromY, toY, pivotXType, pivotXValue, pivotYType, pivotYValueTabHost添加背景图片tabHost.addTab(tabHost.newTabSpec("Second").setIndica tor("Second",getResources().getDrawable(android.R.dra wable.alert_dark_frame)));用Timer获取系统的时间;;@Overridepublicint onStartCommand(Intent intent, int flags, int startId) {timer = new Timer();task = new TimerTask() {@Overridepublicvoid run() {Calendar c = Calendar.getInstance();String time = c.get(Calendar.HOUR_OF_DAY) + ":"+ c.get(Calendar.MINUTE) + ":" +c.get(Calendar.SECOND);System.out.println(time);}};timer.schedule(task, 1000, 1000);returnsuper.onStartCommand(intent, flags, startId);}。

记事本源代码

记事本源代码

记事本源代码先上效果图。

这个记事本操作简便,功能强⼤,在记事本的基础上添加了将内容发送短信和发送邮件的功能。

这个应⽤也已经功过了微软的认证。

115⽹盘⾥⾯的是最新的。

QQ:29992379下载地址:Memo.xap实体类1: public class Note2: {3: public string NoteGuid { get; set; }4: public string NoteContent { get; set; }5: public string NoteTime { get; set; }6: }在独⽴存储中⽣成存储结构。

1: if (!IsolatedStorageSettings.ApplicationSettings.Contains("Notes"))2: {3: List<Note> notes = new List<Note>();4: IsolatedStorageSettings.ApplicationSettings["Notes"] = notes as List<Note>;5: IsolatedStorageSettings.ApplicationSettings.Save();6:7: }绑定⽂章的列表,并按编号倒排序。

1: public partial class MainPage : PhoneApplicationPage2: {3: // 构造函数4: public MainPage()5: {6: InitializeComponent();7: BingData();8: }9: List<Note> notes = new List<Note>();10: private void BingData()11: {12: notes = IsolatedStorageSettings.ApplicationSettings["Notes"] as List<Note>;13:14: var descInfo = from i in notes orderby i.NoteTime descending select i;//linq对⽂章列表的排序15:16: MainListBox.ItemsSource = descInfo;17: }18:19: private void ApplicationBarIconButton_Click(object sender, EventArgs e)20: {21: NavigationService.Navigate(new Uri("/Add.xaml", UriKind.RelativeOrAbsolute));22: }23:24: protected override void OnBackKeyPress(ponentModel.CancelEventArgs e)25: {26: e.Cancel = true;27: App.Quit();28: base.OnBackKeyPress(e);29: }30:31: private void ApplicationBarIconButton_Click_1(object sender, EventArgs e)32: {33: NavigationService.Navigate(new Uri("/About.xaml", UriKind.RelativeOrAbsolute));34: }35:36: private void StackPanel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)37: {38: string noteguid = ((TextBlock)(((StackPanel)sender).Children.First())).Tag.ToString();39: NavigationService.Navigate(new Uri("/DetailsPage.xaml?noteguid=" + noteguid, UriKind.Relative));40: }41: }⽂章显⽰的页⾯以及⼀系列功能1: public partial class DetailsPage : PhoneApplicationPage2: {3: // 构造函数4: public DetailsPage()5: {6: InitializeComponent();7: }8: string noteguid;9: protected override void OnNavigatedTo(NavigationEventArgs e)10: {11: BingData();12: noteguid = NavigationContext.QueryString["noteguid"].ToString();13: foreach (var item in notes)14: {15: if (item.NoteGuid==noteguid)16: {17: ContentText.Text = item.NoteContent;18: TimeText.Text = item.NoteTime;19: return;20: }21: }22: }23:24: List<Note> notes = new List<Note>();25: private void BingData()26: {27: notes = IsolatedStorageSettings.ApplicationSettings["Notes"] as List<Note>;28: }29:30: private void Edit_Click(object sender, EventArgs e)31: {32: NavigationService.Navigate(new Uri("/Edit.xaml?noteguid=" + noteguid.ToString(), UriKind.RelativeOrAbsolute)); 33: }34:35: protected override void OnBackKeyPress(ponentModel.CancelEventArgs e)36: {37: e.Cancel = true;38: NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));39: base.OnBackKeyPress(e);40: }41:42: private void Del_Click(object sender, EventArgs e)43: {44: for (int i = 0; i < notes.Count; i++)45: {46: if (notes[i].NoteGuid==noteguid)47: {48: notes.RemoveAt(i);49: }50: }51: IsolatedStorageSettings.ApplicationSettings["Notes"] = notes as List<Note>;52: IsolatedStorageSettings.ApplicationSettings.Save();53: NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));54: }55:56: private void Email_Click(object sender, EventArgs e)57: {58: EmailComposeTask email = new EmailComposeTask();59: email.Body = ContentText.Text.ToString();60: email.Show();61: }62:63: private void Message_Click(object sender, EventArgs e)64: {65: SmsComposeTask sms = new SmsComposeTask();66: sms.Body = ContentText.Text.ToString();67: sms.Show();68: }69: }⽂章的编辑页⾯代码1: public partial class Edit : PhoneApplicationPage2: {3: public Edit()4: {5: InitializeComponent();6: }7:8: private void ApplicationBarIconButton_Click(object sender, EventArgs e)9: {10: foreach (var item in notes)11: {12: if (item.NoteGuid == noteguid)13: {14: item.NoteContent = ContentText.Text;15: item.NoteTime=TimeText.Text;16: }17: }18:19: IsolatedStorageSettings.ApplicationSettings["Notes"] = notes as List<Note>;20: IsolatedStorageSettings.ApplicationSettings.Save();21: NavigationService.Navigate(new Uri("/DetailsPage.xaml?noteguid=" + noteguid.ToString(), UriKind.RelativeOrAbsolute)); 22: }23: string noteguid;24: protected override void OnNavigatedTo(NavigationEventArgs e)25: {26: BingData();27: noteguid = NavigationContext.QueryString["noteguid"].ToString();28: foreach (var item in notes)29: {30: if (item.NoteGuid==noteguid)31: {32: ContentText.Text = item.NoteContent;33: TimeText.Text = item.NoteTime;34: return;35: }36: }37: }38:39: List<Note> notes = new List<Note>();40: private void BingData()41: {42: notes = IsolatedStorageSettings.ApplicationSettings["Notes"] as List<Note>;43: }44: }。

记事本代码

记事本代码

记事本代码#include<iostream.h>#include<string.h>#include<ctype.h> //为了以下使用isdigit(string)函数作铺垫typedef struct node{char a[100]; //每行100字符node * next; //关于此处next的作用还不清楚,但不可去掉}node;class notepad{public:notepad(){i=1;line=0;}~notepad(){}void operator_interface();void input();void ct_input();void delete1();void copy();void paste();void open();void save();char * find();void print();char store[100]; //储存需复制内容private:char * ptr_array[100]; //指针数组,记录100行行指针int linelen[100]; //最大100行int line; //当前总行数char d[30]; //记录操作数据int k,l; //记录当前查找行ilint i; //文档录入初始标记};void notepad::operator_interface(){cout<<"********************************************************"<<en dl;cout<<"***0.继续录入文档"<<endl;cout<<"***1.输入文档内容"<<endl;cout<<"***2.删除某些内容"<<endl;cout<<"***3.复制某些内容"<<endl;cout<<"***4.粘贴某些内容"<<endl;cout<<"***5.打开文档内容"<<endl;cout<<"***6.是否保存文档"<<endl;cout<<"***7.获取操作帮助"<<endl;cout<<"***8.我要结束操作"<<endl;cout<<"********************************************************"<<en dl;}void notepad::input(){-99"<<endl; cout<<"输入总行数,格式:01char e[10];cin>>e;char *lin=e;if(*(lin+2)=='\0'&&isdigit(*lin)&&isdigit(*(lin+1))){line=(*lin-'0')*10+(*(lin+1)-'0');if(line!=0){cout<<"请输入各行内容"<<endl;while(i<=line){cout<<"第"<<i<<"行 ";node *p=new node;cin>>p->a;ptr_array[i]=p->a;linelen[i]=strlen(p->a);i++;}}else cout<<"你输入的行数有误"<<endl;}else cout<<"你输入的行数有误"<<endl; }void notepad::ct_input(){if(line!=0){int i=line+1;cout<<"输入要录入的总行数,格式:01-99"<<endl;char e[10];cin>>e;char *lin=e;if(*(lin+2)=='\0'&&isdigit(*lin)&&isdigit(*(lin+1))){ line=line+(*lin-'0')*10+(*(lin+1)-'0');if(line!=0){cout<<"请输入各行内容"<<endl;while(i<=line){cout<<"第"<<i<<"行 ";node *p=new node;cin>>p->a;ptr_array[i]=p->a;linelen[i]=strlen(p->a);i++;}}else cout<<"你输入的行数有误"<<endl;}else cout<<"你输入的行数有误"<<endl;}else cout<<"当前文档并无内容,请先输入1录入文档"<<endl; }void notepad::print(){cout<<endl<<endl;int j=1;cout<<"当前文档内容为:"<<endl;while(j<=line){cout<<"第"<<j<<"行 ";char *q=ptr_array[j];while(*q!='\0'){cout<<*q;q++;}cout<<endl;j++;}cout<<endl;}char * notepad::find(){ //暂未解决跨行查找问题k=1;cin>>d;l=strlen(d);char *n=d;int c=1;char *m=ptr_array[k];while(k<=line){if(*m=='\0'){k=k+1;if(k<=line)m=ptr_array[k];}if(*m!='\0'&&*m!=*n)m++;while(*n!='\0'&&*m!='\0'&&*m==*n){ m=m+1;n=n+1;c=c+1;}if(*n=='\0'){return m-c+1;}else {n=d;c=1;}}return NULL;}void notepad::delete1(){char * dp1;char * dp2;cout<<"请输入要删除的文本前几位字符,注意区分"<<endl;dp1=find();int l1=k;cout<<"请输入要删除的文本末几位字符,注意区分"<<endl;dp2=find();int l2=k;if(dp1==NULL||dp2==NULL||l1>l2)cout<<"输入错误"<<endl;else{dp2=dp2+l;if(l1==l2){while(*dp2!='\0'){*dp1=*dp2;dp1++;dp2++;}*dp1='\0';linelen[l1]=strlen(ptr_array[l1]);}else {if(l1+1<l2){for(intt1=l1+1,t2=l2;t2<=line;t1++,t2++)ptr_array[t1]=ptr_array[t2]; line=line-l2+l1+1;l2=l1+1;}*dp1='\0';char *dp21=ptr_array[l2];while(*(dp2-1)!='\0'){*dp21=*dp2;dp21++;dp2++;}linelen[l1]=strlen(ptr_array[l1]);linelen[l2]=strlen(ptr_array[l2]);}if(linelen[l1]==0){for(int v=l1;v<=line;v++)ptr_array[v]=ptr_array[v+1]; line--;}if(linelen[l2]==0){for(int v=l2;v<=line;v++)ptr_array[v]=ptr_array[v+1]; line--;}}}void notepad::copy(){char * cp1;char * cp2;cout<<"请输入要复制的文本前几位字符,注意区分"<<endl; cp1=find();int l1=k;cout<<"请输入要复制的文本末几位字符,注意区分"<<endl; cp2=find();int l2=k;char *pt=store;if(cp1!=NULL&&cp2!=NULL&&l1<=l2){cp2=cp2+l;while(cp1!=cp2){if(*cp1=='\0'){l1++;cp1=ptr_array[l1];}else {*pt=*cp1;pt++;cp1++;}}*pt='\0';}else cout<<"输入错误"<<endl; }void notepad::paste(){cout<<"请输入要粘贴位置的前几位字符(在首字符后粘贴)"<<endl; char *pat=find();if(pat!=NULL){int choice2;cout<<"请选择要粘贴内容:1/从内存中0/我自己输入"<<endl; cin>>choice2;if(!choice2)cin>>store;char *ppt=store;for(char *pat1=pat;*(pat1+1)!='\0';pat1++); //定位至末尾int pl=strlen(store);*(pat1+pl+1)='\0';while(pat1!=pat){ //移位*(pat1+pl)=*pat1;pat1--;}pat++;for(int u=1;u<=pl;u++){*pat=*ppt;ppt++;pat++;}linelen[k]=linelen[k]+pl;}else cout<<"输入错误"<<endl;}void notepad::open(){print();}void notepad::save(){cout<<"是否保存文件,1/是0/否"<<endl;char g[10];int choice1;cin>>g;char *choi=g;if(*(choi+1)=='\0'&&isdigit(*choi)){ choice1=*choi-'0';if(choice1==1)cout<<"文件已保存"<<endl; else if(choice1==0){for(int w=1;w<=line;w++){ //相当于析构函数的作用ptr_array[w]=NULL;linelen[w]=0;}line=0;}else cout<<"输入错误"<<endl;}else cout<<"输入错误"<<endl; }void main(){cout<<"欢迎使用本程序,您可以在要输入文档内容时通过切换输入法实现输入汉字,byhk"<<endl;notepad b;b.operator_interface();char f[10];int choice;cin>>f;char *choic=f;if(*(choic+1)=='\0'&&isdigit(*choic)){ //错误输入处理机制choice=*choic-'0';}else choice=9;while(choice!=8){switch(choice){case 0:b.ct_input();break;case 1:b.input();break;case 2:b.delete1();b.print();break;case 3:{b.copy();cout<<endl;char *p_t=b.store;int fzcd=strlen(b.store);cout<<"你所要复制的内容长度为"<<endl<<fzcd<<endl; cout<<"你所要复制的内容为"<<endl;while(*p_t!='\0'){cout<<*p_t;p_t++;}cout<<endl;}break;case 4:b.paste();b.print();break;case 5:b.open();break;case 6:b.save();break;case 7:b.operator_interface();break;case 8:break;default:break;}if(choice==9||(choice>=0&&choice<=7)){ //输入错误时的操作及输入正确时 //的继续操作判断if(choice==9)cout<<"你输入的操作有误,请重新输入,输入 7 获取操作帮助"<<endl;else cout<<"继续你的操作,输入 7 获取操作帮助"<<endl;cin>>f;choic=f;if(*(choic+1)=='\0'&&isdigit(*choic)) //错误输入处理机制choice=*choic-'0';else choice=9;}}cout<<"感谢您的使用"<<endl; }。

Sqlite安卓记事本

Sqlite安卓记事本

Sqlite_Android记事本实现实现普通记事本的增添,删除,修改功能,可以作为这类应用的一个模版程序使用,手动编写,亲测可用,详细代码如下:1.主界面布局:<RelativeLayoutxmlns:android="/apk/res/android"xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"android:paddingBottom="0dp" tools:context=".MainActivity"><LinearLayoutandroid:gravity="top"android:id="@+id/linlayout_01"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="vertical"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="@string/diary_title"android:layout_gravity="center_horizontal"android:textSize="20dp"/></LinearLayout><ListViewandroid:id="@+id/listview01"android:layout_width="fill_parent"android:layout_height="fill_parent"android:layout_below="@id/linlayout_01"/><LinearLayoutandroid:id="@+id/linlayout_02"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:orientation="vertical"><Buttonandroid:id="@+id/diary_add"android:layout_width="100dp"android:layout_height="100dp"android:layout_gravity="center_horizontal"android:background="@drawable/add"/></LinearLayout></RelativeLayout>2.编辑界面布局<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="/apk/res/android" android:layout_width="fill_parent"android:layout_height="fill_parent"><LinearLayoutandroid:id="@+id/edit_linlayout"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_alignParentTop="true"><TextViewandroid:layout_width="wrap_content"android:layout_weight="0"android:layout_height="wrap_content"android:text="@string/diary_day_edit_biaoti"/> <EditTextandroid:id="@+id/edit_title"android:layout_width="0dp"android:layout_weight="1"android:layout_height="wrap_content"android:hint="请输入标题"/></LinearLayout><EditTextandroid:id="@+id/edit_content"android:layout_below="@id/edit_linlayout"android:layout_above="@+id/edit_save"android:layout_width="fill_parent"android:layout_height="fill_parent"android:gravity="top"/><Buttonandroid:layout_alignParentBottom="true"android:id="@+id/edit_save"android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="@string/edit_save"/></RelativeLayout>3.查看界面布局<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="/apk/res/android" android:layout_width="fill_parent"android:layout_height="fill_parent"><LinearLayoutandroid:id="@+id/look_linlayout"android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_alignParentTop="true"><TextViewandroid:layout_width="wrap_content"android:layout_weight="0"android:layout_height="wrap_content"android:text="@string/diary_day_edit_biaoti"/> <TextViewandroid:id="@+id/look_title"android:layout_width="0dp"android:layout_weight="1"android:layout_height="wrap_content"/></LinearLayout><TextViewandroid:id="@+id/look_content"android:layout_below="@id/look_linlayout"android:layout_width="fill_parent"android:layout_height="fill_parent"</RelativeLayout>4.主界面显示布局<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android" android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal"><TextViewandroid:id="@+id/diary_day_title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10px"android:gravity="center_vertical|left"/></LinearLayout>5.主界面package com.example.diary;import android.app.Activity;import android.app.AlertDialog;import android.app.AlertDialog.Builder;import android.content.DialogInterface;import android.content.Intent;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.view.ContextMenu;import android.view.ContextMenu.ContextMenuInfo;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.Window;import android.widget.AdapterView;import android.widget.AdapterView.AdapterContextMenuInfo;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.Toast;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class MainActivity extends Activity {Button bt_add;ListView listView;private SQLiteDatabase sdb;private DBhelper dBhelper;private SimpleAdapter sa;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(yout.activity_main);listView = (ListView) findViewById(R.id.listview01);bt_add = (Button) findViewById(R.id.diary_add);dBhelper = new DBhelper(MainActivity.this);//获取数据库数据bt_add.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Intent intent = new Intent();intent.setClass(MainActivity.this, activity_add.class); startActivity(intent);}});show();//listView按键监听,单机查看单项数据listView.setOnItemClickListener(new OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {// TODO Auto-generated method stubMap<String, Object> map = (Map<String, Object>) arg0.getItemAtPosition(arg2);Intent intent = new Intent();intent.putExtra("diary_id",map.get("diary_id").toString());//传递列表id值intent.setClass(MainActivity.this,LookActivity.class);startActivity(intent);}});//长按事件监听listView.setOnItemLongClickListener(new OnItemLongClickListener() {@Overridepublic boolean onItemLongClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {// TODO Auto-generated method stubfinal Map<String, Object> map = (Map<String, Object>) arg0.getItemAtPosition(arg2);AlertDialog.Builder aBuilder = newBuilder(MainActivity.this);aBuilder.setTitle(map.get("diary_title").toString());aBuilder.setItems(new String[]{"删除","修改"}, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubswitch (which) {case 0://删除sdb =dBhelper.getWritableDatabase();try {sdb.delete("diary", "diary_id=?",new String[] {map.get("diary_id").toString()});} catch (Exception e) {// TODO: handle exceptionToast.makeText(MainActivity.this, "删除失败",Toast.LENGTH_SHORT).show();}sdb.close();show();break;case 1://修改Intent intent = new Intent();intent.putExtra("diary_id", map.get("diary_id").toString());intent.setClass(MainActivity.this, activity_add.class);startActivity(intent);break;default:break;}}});aBuilder.show();return false;}});}//主界面显示函数public void show(){sdb = dBhelper.getReadableDatabase();//获取数据库读权限//rawQuery 用于执行select语句Cursor cursor = sdb.rawQuery("select diary_id,diary_title from diary",null);List<Map<String,Object>> list = newArrayList<Map<String,Object>>();//创建list用于保存map数据while (cursor.moveToNext()){Map<String,Object> map = new HashMap<String, Object>();//map 用于保存数据库数据String str_title =cursor.getString(cursor.getColumnIndex("diary_title"));//处理标题长度限制if (str_title.length()> 20 ){map.put("diary_title",str_title.substring(0,20) + "..."); }else {map.put("diary_title",str_title);}map.put("diary_id",cursor.getString(cursor.getColumnIndex("diary_id"))); list.add(map);}cursor.close();//关闭cursor释放内存空间//新建适配器,list作为数据源,map不能sa = new SimpleAdapter(MainActivity.this,list,yout.list_items,new String[] {"diary_title"},new int[]{R.id.diary_day_title});listView.setAdapter(sa);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId();//noinspection SimplifiableIfStatementif (id == R.id.action_settings) {return true;}return super.onOptionsItemSelected(item);}}6.添加,编辑package com.example.diary;import android.R.string;import android.app.Activity;import android.content.ContentValues;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.widget.Button;import android.widget.EditText;/*** Created by Alex on 2015/9/25.*/public class activity_add extends Activity{private EditText edit_title,edit_content;private Button bt_save;private SQLiteDatabase sdb;private DBhelper dBhelper;static String tag = "database";private static String diary_id,str_title,str_content;protected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.diary_edit);edit_title = (EditText) findViewById(R.id.edit_title);edit_content = (EditText) findViewById(R.id.edit_content);bt_save = (Button) findViewById(R.id.edit_save);dBhelper = new DBhelper(activity_add.this);Intent intent = getIntent();diary_id = intent.getStringExtra("diary_id");//diary_id不为空,则是编辑if (diary_id != null) {sdb = dBhelper.getReadableDatabase();Cursor cursor = sdb.query("diary", newString[]{"diary_id","diary_title","diary_content"},"diary_id=?", new String[]{diary_id}, null, null, null);while (cursor.moveToNext()) {str_title =cursor.getString(cursor.getColumnIndex("diary_title"));str_content =cursor.getString(cursor.getColumnIndex("diary_content"));Log.d(tag, str_title);Log.d(tag, str_content);}edit_title.setText(str_title);edit_content.setText(str_content);cursor.close();sdb.close();}bt_save.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if (diary_id == null){add_save();}else {edit_save();}Intent intent = new Intent();intent.setClass(activity_add.this,MainActivity.class); startActivity(intent);}});}//编辑操作public void edit_save(){sdb = dBhelper.getWritableDatabase();String title = edit_title.getText().toString();String content = edit_content.getText().toString();try {ContentValues cValues = new ContentValues();cValues.put("diary_title", title);cValues.put("diary_content", content);sdb.update("diary", cValues, "diary_id=?", newString[]{diary_id});} catch (Exception e) {// TODO: handle exceptionLog.v(tag,"更新失败");}sdb.close();}//保存操作public void add_save(){sdb = dBhelper.getWritableDatabase();String title = edit_title.getText().toString();String content = edit_content.getText().toString();try {ContentValues cValues = new ContentValues();cValues.put("diary_title", title);cValues.put("diary_content", content);sdb.insert("diary", null, cValues);}catch (Exception e){String tag = "database";Log.v(tag,"插入失败");}sdb.close();}}7.查看package com.example.diary;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.widget.TextView;public class LookActivity extends Activity{/*** @param args*/private TextView tv_title,tv_content;private SQLiteDatabase sdb;private DBhelper dBhelper;private String diary_id,str_title,str_content;protected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.diary_lookover);tv_title = (TextView) findViewById(R.id.look_title);tv_content = (TextView) findViewById(R.id.look_content);//获取intent传递的数据Intent intent = getIntent();diary_id = intent.getStringExtra("diary_id");dBhelper = new DBhelper(LookActivity.this);sdb = dBhelper.getReadableDatabase();//两种查询的方式;1是rawQuery;2是直接调用queryCursor cursor = sdb.rawQuery("select diary_title,diary_content from diary where diary_id=?" , new String[]{diary_id});// Cursor cursor = sdb.query("diary", newString[]{"diary_id","diary_title","diary_content"},// "diary_id=?", new String[]{diary_id}, null, null, null);while (cursor.moveToNext()) {str_title =cursor.getString(cursor.getColumnIndex("diary_title"));str_content =cursor.getString(cursor.getColumnIndex("diary_content"));}tv_title.setText(str_title);tv_content.setText(str_content);cursor.close();sdb.close();}}8.数据庫package com.example.diary;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.os.Bundle;import android.widget.TextView;public class LookActivity extends Activity{/*** @param args*/private TextView tv_title,tv_content;private SQLiteDatabase sdb;private DBhelper dBhelper;private String diary_id,str_title,str_content;protected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(yout.diary_lookover);tv_title = (TextView) findViewById(R.id.look_title);tv_content = (TextView) findViewById(R.id.look_content);//获取intent传递的数据Intent intent = getIntent();diary_id = intent.getStringExtra("diary_id");dBhelper = new DBhelper(LookActivity.this);sdb = dBhelper.getReadableDatabase();//两种查询的方式;1是rawQuery;2是直接调用queryCursor cursor = sdb.rawQuery("select diary_title,diary_content from diary where diary_id=?" , new String[]{diary_id});// Cursor cursor = sdb.query("diary", newString[]{"diary_id","diary_title","diary_content"},// "diary_id=?", new String[]{diary_id}, null, null, null);while (cursor.moveToNext()) {str_title =cursor.getString(cursor.getColumnIndex("diary_title"));str_content =cursor.getString(cursor.getColumnIndex("diary_content"));}tv_title.setText(str_title);tv_content.setText(str_content);cursor.close();sdb.close();}}。

Android实现记事本功能(26)

Android实现记事本功能(26)

Android实现记事本功能(26)本⽂实例为⼤家分享了Android实现记事本功能的具体代码,供⼤家参考,具体内容如下MainActivity.java代码:package siso.smartnotef.activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.view.ViewGroup;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.TextView;import java.util.ArrayList;import java.util.List;import siso.smartnotef.R;import siso.smartnotef.adapter.NotepadeAdapter;import siso.smartnotef.db.DataHelper;import siso.smartnotef.global.GlobalParams;import siso.smartnotef.model.NotepadBean;import siso.smartnotef.model.NotepadWithDataBean;import siso.smartnotef.service.MainService;public class MainActivity extends AppCompatActivity implements View.OnClickListener, NotepadeAdapter.ClickFunction {private TextView tv_add;private ListView lv_contents;private List<NotepadWithDataBean> notepadWithDataBeanList;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);Intent intent1 = new Intent(MainActivity.this, MainService.class);startService(intent1);findViews();setListeners();initView();}private void findViews() {tv_add = (TextView) findViewById(_add);lv_contents = (ListView) findViewById(R.id.lv_content);}private void setListeners() {tv_add.setOnClickListener(this);}private void initView() {DataHelper helper = new DataHelper(MainActivity.this);notepadWithDataBeanList = new ArrayList<NotepadWithDataBean>();List<NotepadBean> notepadBeanList = helper.getNotepadList();for (int i = 0; i < notepadBeanList.size(); i++) {if (0 == notepadWithDataBeanList.size()) {NotepadWithDataBean notepadWithDataBean = new NotepadWithDataBean();notepadWithDataBean.setData(notepadBeanList.get(0).getDate());notepadWithDataBeanList.add(notepadWithDataBean);}boolean flag = true;for (int j = 0; j < notepadWithDataBeanList.size(); j++) {int date = notepadWithDataBeanList.get(j).getData();if (date == notepadBeanList.get(i).getDate()) {notepadWithDataBeanList.get(j).getNotepadBeenList().add(notepadBeanList.get(i));flag = false;break;}}if (flag) {NotepadWithDataBean notepadWithDataBean = new NotepadWithDataBean();notepadWithDataBean.setData(notepadBeanList.get(i).getDate());notepadWithDataBeanList.add(notepadWithDataBean);notepadWithDataBeanList.get(notepadWithDataBeanList.size() - 1).getNotepadBeenList().add(notepadBeanList.get(i));}}NotepadeAdapter adapter = new NotepadeAdapter(MainActivity.this, notepadWithDataBeanList, this);lv_contents.setAdapter(adapter);// setListViewHeightBasedOnChildren(lv_contents);}public void setListViewHeightBasedOnChildren(ListView listView) {if (listView == null) return;ListAdapter listAdapter = listView.getAdapter();if (listAdapter == null) {// pre-conditionreturn;}int totalHeight = 0;for (int i = 0; i < listAdapter.getCount(); i++) {View listItem = listAdapter.getView(i, null, listView);listItem.measure(0, 0);totalHeight += listItem.getMeasuredHeight();}youtParams params = listView.getLayoutParams();params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));listView.setLayoutParams(params);}@Overridepublic void onClick(View v) {switch (v.getId()) {case _add:Intent intent = new Intent();Bundle bundle = new Bundle();bundle.putInt(GlobalParams.TYPE_KEY, GlobalParams.TYPE_ADD);intent.putExtras(bundle);intent.setClass(MainActivity.this, AddContentActivity.class);startActivityForResult(intent, GlobalParams.ADD_REQUEST);break;}}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);switch (requestCode) {case GlobalParams.ADD_REQUEST:if (GlobalParams.ADD_RESULT_OK == resultCode) {initView();}break;}}@Overridepublic void clickItem(int position, int itemPosition) {Bundle bundle = new Bundle();bundle.putInt(GlobalParams.TYPE_KEY, GlobalParams.TYPE_EDIT);bundle.putSerializable(GlobalParams.BEAN_KEY, notepadWithDataBeanList.get(position));bundle.putInt(GlobalParams.ITEM_POSITION_KEY, itemPosition);Intent intent = new Intent(this, AddContentActivity.class);intent.putExtras(bundle);startActivityForResult(intent, GlobalParams.ADD_REQUEST);}@Overridepublic void longClickItem(final int position, final int itemPostion) {AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);builder.setMessage("确认删除吗?");builder.setTitle("提⽰");builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {DataHelper helper = new DataHelper(MainActivity.this);helper.deleteNotepad(notepadWithDataBeanList.get(position).getNotepadBeenList().get(itemPostion).getId()); initView();}});builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});builder.create().show();}}AddContentActivity.java代码:package siso.smartnotef.activity;import android.app.DatePickerDialog;import android.app.TimePickerDialog;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.DatePicker;import android.widget.EditText;import android.widget.TextView;import android.widget.TimePicker;import android.widget.Toast;import java.util.Calendar;import siso.smartnotef.R;import siso.smartnotef.db.DataHelper;import siso.smartnotef.global.GlobalParams;import siso.smartnotef.model.NotepadBean;import siso.smartnotef.model.NotepadWithDataBean;public class AddContentActivity extends AppCompatActivity implements View.OnClickListener {private TextView tv_save;private TextView tv_date;private TextView tv_time;private TextView tv_cancel;private EditText et_content;private String time = "";private String date = "";private Bundle bundle;private int type;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_add_content);bundle=getIntent().getExtras();type=bundle.getInt(GlobalParams.TYPE_KEY);findViews();setListeners();initDate();}private void findViews() {et_content=(EditText)findViewById(R.id.et_content);tv_save = (TextView) findViewById(_save);tv_date = (TextView) findViewById(_date);tv_time = (TextView) findViewById(_time);tv_cancel=(TextView)findViewById(_cancel);}private void setListeners() {tv_save.setOnClickListener(this);tv_date.setOnClickListener(this);tv_time.setOnClickListener(this);tv_cancel.setOnClickListener(this);}private void initDate() {Calendar c = Calendar.getInstance();int year=c.get(Calendar.YEAR);int month=c.get(Calendar.MONTH);int day=c.get(Calendar.DAY_OF_MONTH);date=getDate(year,month,day);if(type==GlobalParams.TYPE_EDIT){NotepadWithDataBean notepadWithDataBean=(NotepadWithDataBean)(bundle.getSerializable(GlobalParams.BEAN_KEY));et_content.setText(notepadWithDataBean.getNotepadBeenList().get(bundle.getInt(GlobalParams.ITEM_POSITION_KEY)).getContent()); date=notepadWithDataBean.getData()+"";tv_date.setText(date);time=notepadWithDataBean.getNotepadBeenList().get(bundle.getInt(GlobalParams.ITEM_POSITION_KEY)).getTime();tv_time.setText(time);}}private String getDate(int year,int month,int day){String date="";date+=year;if(month<9){date=date+"0"+(month+1);}else{date+=(month+1);}if(day<10){date=date+"0"+day;}else {date+=day;}return date;}@Overridepublic void onClick(View v) {switch (v.getId()) {case _save:if(type==GlobalParams.TYPE_EDIT){update();}else {save();}break;case _date:selectDateDialog();break;case _time:selectTimeDialog();break;case _cancel:finish();break;}}private void selectDateDialog(){Calendar c = Calendar.getInstance();int year=c.get(Calendar.YEAR);final int month=c.get(Calendar.MONTH)+1;int day=c.get(Calendar.DAY_OF_MONTH);new DatePickerDialog(AddContentActivity.this, new DatePickerDialog.OnDateSetListener() {@Overridepublic void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {date=getDate(year,monthOfYear,dayOfMonth);tv_date.setText(date);}},year,month,day).show();}private void selectTimeDialog() {Calendar c = Calendar.getInstance();int mHour = c.get(Calendar.HOUR_OF_DAY);int mMinute = c.get(Calendar.MINUTE);new TimePickerDialog(AddContentActivity.this,new TimePickerDialog.OnTimeSetListener() {@Overridepublic void onTimeSet(TimePicker view,int hourOfDay, int minute) {time=formatTime(hourOfDay,minute);tv_time.setText(time);}}, mHour, mMinute, true).show();}private String formatTime(int hour,int minute){String time=hour+":";if(minute<10){time=time+"0"+minute;}else{time+=minute;}return time;}private void save() {String content = et_content.getText().toString();if ("".equals(content)) {Toast.makeText(AddContentActivity.this, "请输⼊内容", Toast.LENGTH_SHORT).show();return;}if ("".equals(time)) {Toast.makeText(AddContentActivity.this, "请选择时间", Toast.LENGTH_SHORT).show();return;}NotepadBean notepadBean = new NotepadBean();notepadBean.setContent(content);notepadBean.setDate(Integer.parseInt(date));notepadBean.setTime(time);DataHelper helper = new DataHelper(AddContentActivity.this);helper.insertData(notepadBean);setResult(GlobalParams.ADD_RESULT_OK);finish();}private void update(){DataHelper helper=new DataHelper(AddContentActivity.this);NotepadWithDataBean bean=(NotepadWithDataBean)(bundle.getSerializable(GlobalParams.BEAN_KEY)); int itemPosition=bundle.getInt(GlobalParams.ITEM_POSITION_KEY);helper.update(bean.getNotepadBeenList().get(itemPosition).getId(),date,time,et_content.getText().toString()); setResult(GlobalParams.ADD_RESULT_OK);finish();}}RemindActivity.java代码:package siso.smartnotef.activity;import android.media.MediaPlayer;import android.media.RingtoneManager;import .Uri;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView;import java.io.IOException;import siso.smartnotef.R;import siso.smartnotef.global.GlobalParams;public class RemindActivity extends AppCompatActivity {private TextView tv_content;private Button bt_confirm;private MediaPlayer mMediaPlayer;;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_remind);findViews();setListeners();Bundle bundle=getIntent().getExtras();String content=bundle.getString(GlobalParams.CONTENT_KEY);tv_content.setText(content);playSound();}private void findViews(){tv_content=(TextView)findViewById(_content);bt_confirm=(Button) findViewById(R.id.bt_confirm);}private void setListeners(){bt_confirm.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {if(null!=mMediaPlayer){mMediaPlayer.stop();finish();}}});}public void playSound() {new Thread(new Runnable() {@Overridepublic void run() {mMediaPlayer = MediaPlayer.create(RemindActivity.this, getSystemDefultRingtoneUri()); mMediaPlayer.setLooping(true);//设置循环try {mMediaPlayer.prepare();} catch (IllegalStateException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}mMediaPlayer.start();}}).start();}//获取系统默认铃声的Uriprivate Uri getSystemDefultRingtoneUri() {return RingtoneManager.getActualDefaultRingtoneUri(RemindActivity.this,RingtoneManager.TYPE_RINGTONE);}}activity_main.xml内容:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android"xmlns:tools="/tools"android:id="@+id/activity_main"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="siso.smartnotef.activity.MainActivity"><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="50dp"android:background="@color/title_color"android:paddingLeft="10dp"android:paddingRight="10dp"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="@color/white"android:textSize="18sp"android:layout_centerInParent="true"android:text="智能记事本"/><TextViewandroid:id="@+id/tv_add"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="@color/white"android:text="新增"android:layout_centerVertical="true"android:layout_alignParentRight="true"android:textSize="13sp"/></RelativeLayout><ListViewandroid:id="@+id/lv_content"android:layout_width="match_parent"android:layout_height="wrap_content"></ListView></LinearLayout>activity_add_content.xml内容:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android" xmlns:tools="/tools"android:id="@+id/activity_add_content"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"tools:context="siso.smartnotef.activity.AddContentActivity"><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="50dp"android:background="@color/title_color"android:paddingLeft="10dp"android:paddingRight="10dp"><TextViewandroid:id="@+id/tv_cancel"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:text="取消"android:textColor="@color/white"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="@color/white"android:textSize="18sp"android:layout_centerInParent="true"android:text="智能记事本"/><TextViewandroid:id="@+id/tv_save"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textColor="@color/white"android:text="保存"android:layout_centerVertical="true"android:layout_alignParentRight="true"/></RelativeLayout><LinearLayoutandroid:layout_marginTop="10dp"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"android:layout_gravity="center_horizontal"><TextViewandroid:id="@+id/tv_date"android:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="5dp"android:text="今天"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text=" -- "/><TextViewandroid:id="@+id/tv_time"android:layout_width="wrap_content"android:layout_height="wrap_content"android:padding="5dp"android:text="请选择时间"/></LinearLayout><EditTextandroid:id="@+id/et_content"android:layout_marginTop="10dp"android:layout_width="match_parent"android:layout_height="match_parent"android:inputType="textMultiLine"android:gravity="left|top"android:layout_margin="20dp"android:padding="10dp"android:hint="请输⼊内容"android:background="@drawable/edit_back"/></LinearLayout>activity_remind.xml内容:<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android" xmlns:tools="/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@color/white"android:orientation="vertical"tools:context="siso.smartnotef.activity.RemindActivity"><TextViewandroid:id="@+id/tv_content"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal" /><Buttonandroid:id="@+id/bt_confirm"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_horizontal"android:text="取消" /></LinearLayout>AndroidManifest.xml内容:<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="/apk/res/android"package="siso.smartnotef"><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/Theme.AppCompat.Light.NoActionBar"><activityandroid:name=".activity.MainActivity"android:theme="@style/Theme.AppCompat.Light.NoActionBar"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="UNCHER" /></intent-filter></activity><receiver android:name=".receiver.MainReceiver"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" /></intent-filter></receiver><activity android:name=".activity.AddContentActivity" /><serviceandroid:name=".service.MainService"android:enabled="true"android:exported="true" /><activity android:name=".activity.RemindActivity"></activity></application></manifest>项⽬结构如图:项⽬运⾏结果如图:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

记事本代码

记事本代码
Dim s As String = InputBox("请输入要查找的文本", Me.Text, "", Me.rtbNote.Location.X + Me.rtbNote.Width / 2, Me.rtbNote.Location.Y + Height / 2)
Dim i As Integer = Me.rtbNote.Find(s)
Public Class FrmNoteBook
Private Const DEFAULTFILE As String = "NewFile"
Private currentFile As String = ""
Private bChanged As Boolean = False
End If
Me.bChanged = False
End Sub
Private Sub saveAs()
Dim dlg As New SaveFileDialog
dlg.Title = "另存为"
dlg.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*"
Me.rtbNote .Paste
End Sub
'处理剪切
Private Sub miCut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles miCut.Click
Else
Me.rtbNote.WordWrap = False
End If

记事本程序源代码汇总

记事本程序源代码汇总

import java.awt.event.*;import java.awt.*;import java.io.*;import ng.String;class jsb implements ActionListener{Dialog bb;String strt;int i;FileDialog fd;File file;public Frame f;public TextArea p1;public MenuBar menubar;public Menu menu1,menu2,menu3;public MenuItem item1,item2,item3,item4,item5,item6,item7,item8,item9,item10; jsb(String s{ i=0;f=new Frame(s;p1=new TextArea("";f.setSize(500,500;f.setBackground(Color.white;f.setVisible(true;menubar=new MenuBar(;menu1=new Menu("文件";menu2=new Menu("编辑";menu3=new Menu("帮助";item1=new MenuItem("新建";item2=new MenuItem("打开";item3=new MenuItem("保存";item4=new MenuItem("另存为";item5=new MenuItem("退出";item6=new MenuItem("全选";item7=new MenuItem("复制";item8=new MenuItem("剪切";item9=new MenuItem("粘贴";item10=new MenuItem("关于";f.addWindowListener(new WindowAdapter({public void windowClosing(WindowEvent e {f.setVisible(false;System.exit(0;}};menu1.add(item1;menu1.add(item2;menu1.add(item3;menu1.add(item4;menu1.add(item5;menu2.add(item6;menu2.add(item7;menu2.add(item8;menu2.add(item9;menu3.add(item10;menubar.add(menu1;menubar.add(menu2;menubar.add(menu3;f.setMenuBar(menubar;item1.addActionListener(this;item2.addActionListener(this;item3.addActionListener(this;item4.addActionListener(this;item5.addActionListener(this;item6.addActionListener(this;item7.addActionListener(this;item8.addActionListener(this;item9.addActionListener(this;item10.addActionListener(this;f.setLayout(new GridLayout(1,1;f.add(p1;f.pack(;}public void actionPerformed(ActionEvent e { String ss;ss=p1.getText(.trim(;if (e.getSource(==item5{if (i==0 &&(ss.length(!=0{bc(;}else{System.exit(0;}}if (e.getSource(==item1{if (i==0&&(ss.length(!=0{bc(;}else{p1.setText("";i=0;f.setTitle("文件对话框"; } }if (e.getSource(==item2{fd=new FileDialog(f,"打开文件",0;fd.setVisible(true;try{file=new File(fd.getDirectory(,fd.getFile(;f.setTitle(fd.getFile(+"文件对话框"; FileReader fr=new FileReader(file; BufferedReader br=new BufferedReader(fr; String line = null;String view = "";while((line=br.readLine(!=null{view += line+"\n";}p1.setText(view;br.close(;fr.close(;}catch(IOException expIn{}}if (e.getSource(==item3{if (i==0{bc(;}else{try{file=new File(fd.getDirectory(,fd.getFile(;f.setTitle(fd.getFile(+"--记事本";FileWriter fw=new FileWriter(file; BufferedWriter bw=new BufferedWriter(fw; String s =p1.getText(;s = s.replaceAll("\n","\r\n";bw.write(s;bw.flush(;bw.close(;fw.close(;i=1;}catch(IOException expOut{i=0;}}}if (e.getSource(==item4{bc(;}if (e.getSource(==item10{bb=new Dialog(f,"关于";Label l1=new Label("本记事本的完成感谢老师和同学的帮助!!"; bb.add(l1; bb.setSize(250,150;bb.setBackground(Color.white;bb.show(;bb.addWindowListener(new WindowAdapter({public void windowClosing(WindowEvent e{bb.setVisible(false;bb.dispose(;}};}if (e.getSource(==item6{p1.setSelectionStart(0;p1.setSelectionEnd(p1.getText(.length(; }if (e.getSource(==item7{try{String str=p1.getSelectedText(;if(str.length(!=0{strt=str;}}catch(Exception ex{}}if (e.getSource(==item8{try{String str=p1.getSelectedText(;if(str.length(!=0{p1.replaceRange("",p1.getSelectionStart(,p1.getSelectionEnd(; } }catch(Exception ex{}}if (e.getSource(==item9{if(strt.length(>0{p1.insert(strt,p1.getCaretPosition(;}}}public void bc({fd=new FileDialog(f,"保存文件",1;fd.setVisible(true;try{file=new File(fd.getDirectory(,fd.getFile(;f.setTitle(fd.getFile(+"--记事本"; FileWriter fw=new FileWriter(file; BufferedWriter bw=new BufferedWriter(fw; String s =p1.getText(;s = s.replaceAll("\n","\r\n";bw.write(s;bw.flush(;bw.close(;fw.close(;i=1;}catch(IOException expOut{}} } public class EX0101 { public static void main(String args[] {jsb dd=new jsb("我的记事本";} }。

Android记事本开发实例详解

Android记事本开发实例详解

这个ac<action android:name="android.intent.action.VIEW" /><action android:name="android.intent.action.EDIT" /><action android:name="com.android.notepad.action.EDIT_NOTE" /><category android:name="android.intent.category.DEFAULT" /><data android:mimeType="vnd.android.cursor.item/vnd.google.note" /></intent-filter><!-- This filter says that we can create a new note inside of a directory of notes. --><intent-filter><action android:name="android.intent.action.INSERT" /><category android:name="android.intent.category.DEFAULT" /><data android:mimeType="vnd.android.cursor.dir/vnd.google.note" /></intent-filter></activity>上面第一个intent-filter中有一个action 名为android.intent.action.EDIT,而前面我们创建的Intent也正好是Intent.ACTION_EDIT=” android.intent.action.EDIT”,想必大家已经明白是怎么回事了吧。

记事本源代码

记事本源代码

import java.awt.*;import java.awt.event.*;import java.io.*;import java.awt.datatransfer.*;class MyMenuBar extends MenuBar{public MyMenuBar(Frame parent){parent.setMenuBar(this);}public void addMenus(String [] menus){for(int i=0;i<menus.length;i++)add(new Menu(menus[i]));}public void addMenuItems(int menuNumber,String[] items){for(int i=0;i<items.length;i++){if(items[i]!=null)getMenu(menuNumber).add(new MenuItem(items[i]));else getMenu(menuNumber).addSeparator();}}public void addActionListener(ActionListener al){for(int i=0;i<getMenuCount();i++)for(int j=0;j<getMenu(i).getItemCount();j++)getMenu(i).getItem(j).addActionListener(al);}}class MyFile{private FileDialog fDlg;public MyFile(Frame parent){fDlg=new FileDialog(parent,"",FileDialog.LOAD);}private String getPath(){return fDlg.getDirectory()+"\\"+fDlg.getFile();}public String getData() throws IOException{fDlg.setTitle("打开");fDlg.setMode(FileDialog.LOAD);fDlg.setV isible(true);BufferedReader br=new BufferedReader(new FileReader(getPath()));StringBuffer sb=new StringBuffer();String aline;while((aline=br.readLine())!=null)sb.append(aline+'\n');br.close();return sb.toString();}public void setData(String data) throws IOException{fDlg.setTitle("保存");fDlg.setMode(FileDialog.SA VE);fDlg.setV isible(true);BufferedWriter bw=new BufferedWriter(new FileWriter(getPath()));bw.write(data);bw.close();}}class MyClipboard{private Clipboard cb;public MyClipboard(){cb=Toolkit.getDefaultToolkit().getSystemClipboard();}public void setData(String data){cb.setContents(new StringSelection(data),null);}public String getData(){Transferable content=cb.getContents(null);try{return (String) content.getTransferData(DataFlavor.stringFlavor);//DataFlavor.stringFlavor会将剪贴板中的字符串转换成Unicode码形式的String 对象。

android开发记事本实验报告,记事本实验报告(含源代码运行结果).doc

android开发记事本实验报告,记事本实验报告(含源代码运行结果).doc

android开发记事本实验报告,记事本实验报告(含源代码运⾏结果).doc记事本实验报告(含源代码运⾏结果)嘉应学院计算机学院实验报告系/班别: 计算机学院 1203班指导⽼师: 肖**课程名称: Java语⾔程序设计实验内容: ⽤Java编写记事本学⽣学号:学⽣姓名: 曾朝阳实验地点: 锡科403实验类型: 设计实验时间: 第⼗四周⾄第⼗七周实验要求:能够通过使⽤JDK1.6安装开发windows 桌⾯应⽤程序。

实验⽬的:熟悉事件触发和事件监听以及组件和容器的界⾯安排,能够⽤java设计⼀个仿windows的标准型记事本。

实验过程描述:实验环境:⽹络实验室实验设备:PC机, ⽹络实验平台:winxp. JDK1.6过程描述:1.⾸先,安装JDK1.62.打开开始-》运⾏->输⼊cmd进⼊dos->cd 路径(原程序的路径)->javac NotepadTest.java(编绎)->java NotepadTest运⾏编写程序:import java.io.File;import .URLClassLoader;import .URL;import ng.InterruptedException;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.PrintStream;import java.util.Scanner;import java.util.Date;import java.util.Iterator;import java.util.List;import java.text.SimpleDateFormat; import javax.swing.JButton;import javax.swing.JCheckBox;import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.ImageIcon;import javax.swing.JScrollPane;import javax.swing.JToolBar;import javax.swing.JMenuItem;import javax.swing.KeyStroke;import javax.swing.JPopupMenu;import javax.swing.JFileChooser;import javax.swing.JOptionPane;import javax.swing.JFileChooser;import javax.swing.JColorChooser; import javax.swing.JDialog;import javax.swing.JTextField;import javax.swing.BorderFactory;import javax.swing.JList;import javax.swing.JComboBox;import javax.swing.UIManager;import javax.swing.JRadioButton;import javax.swing.JToggleButton;import javax.swing.ButtonGroup;import javax.swing.TransferHandler;import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.text.Document; import javax.swing.undo.UndoManager; import javax.swing.undo.UndoableEdit; import。

记事本java源代码

记事本java源代码

import java.awt.BorderLayout;import java.awt.Font;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.InputEvent;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;import java.awt.event.KeyEvent;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import javax.swing.JCheckBoxMenuItem;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JOptionPane;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.KeyStroke;/*** TXT记事本** @author Administrator**/public class Notepad implements WindowListener, ActionListener, ItemListener { /*** 本程序的主界面框体*/private JFrame frame;/*** 记事本名*/private String txtName = "无标题";/*** 文本区域*/private JTextArea center = new JTextArea();/*** 滚动条*/private JScrollPane pane = new JScrollPane(center);/*** 菜单条*/private JMenuBar menuBar = new JMenuBar();/*** 菜单文件,系统,设置字体*/private JMenu fileMenu, systemMenu, setFont;/*** 菜单项新建,打开,保存,另存,退出,字号变大,字号变小,关于,宋体,楷体,黑体,隶书*/private JMenuItem newItem, openItem, saveItem, saveAsItem, exitItem,larger, smaller, about,songItem,kaiItem,heiItem,liItem;/*** 自动换行*/private JCheckBoxMenuItem autoChangeLine;private boolean judge = false; // 判断是否需要自动换行/*** 文件选择器*/private JFileChooser chooser = new JFileChooser();/*** 当前文件*/private File currentFile = null;/*** 当新建或打开或退出时判断文本区内容是否改变*/private String compareTxt;/*** 当前字体*/private Font font;/*** 当前字号*/private int fontSize;/*** 当前字体的名字*/private String fontName;/*** 初始化框体*/private void initMainFrame() {if (frame == null) {// 创建窗体组件frame = new JFrame();// 窗体标题frame.setTitle(txtName + "\t"+"记事本");// 设置位置、尺寸int width = 500;int height = 500;// 获取屏幕的宽和高frame.setSize(width, height);// 设置右上角关闭按钮的默认操作frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);frame.addWindowListener(this);frame.setLocationRelativeTo(null);//居中}}/*** 显示框体*/private void show() {frame.setVisible(true);}/*** 框体初始化*/private void initComponent() {// 设置容器型组件的布局管理器frame.setLayout(new BorderLayout());// 初始化菜单fileMenu = new JMenu("文件(F)");fileMenu.setMnemonic(KeyEvent.VK_F);systemMenu = new JMenu("系统(S)");systemMenu.setMnemonic(KeyEvent.VK_S);setFont = new JMenu("设置字体");// 初始化菜单项newItem = new JMenuItem("新建");newItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK));newItem.addActionListener(this);openItem = new JMenuItem("打开");openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK));openItem.addActionListener(this);saveItem = new JMenuItem("保存");saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_DOWN_MASK));saveItem.addActionListener(this);saveAsItem = new JMenuItem("另存为(A)");saveAsItem.setMnemonic(KeyEvent.VK_A);saveAsItem.addActionListener(this);exitItem = new JMenuItem("退出(X)");exitItem.setMnemonic(KeyEvent.VK_X);exitItem.addActionListener(this);larger = new JMenuItem("放大");larger.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_UP,InputEvent.CTRL_DOWN_MASK));larger.addActionListener(this);smaller = new JMenuItem("缩小");smaller.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,InputEvent.CTRL_DOWN_MASK));smaller.addActionListener(this);autoChangeLine = new JCheckBoxMenuItem("自动换行(W)");autoChangeLine.setMnemonic(KeyEvent.VK_W);autoChangeLine.addItemListener(this);about = new JMenuItem("关于(A)");about.setMnemonic(KeyEvent.VK_A);about.addActionListener(this);songItem=new JMenuItem("宋体");songItem.addActionListener(this);kaiItem=new JMenuItem("楷体");kaiItem.addActionListener(this);heiItem=new JMenuItem("黑体");heiItem.addActionListener(this);liItem=new JMenuItem("隶书");liItem.addActionListener(this);// 文件菜单fileMenu.add(newItem);fileMenu.add(openItem);fileMenu.add(saveItem);fileMenu.add(saveAsItem);fileMenu.addSeparator();fileMenu.add(exitItem);// 系统菜单systemMenu.add(setFont);systemMenu.add(larger);systemMenu.add(smaller);systemMenu.add(autoChangeLine);systemMenu.addSeparator();systemMenu.add(about);//设置字体菜单setFont.add(songItem);setFont.add(kaiItem);setFont.add(heiItem);setFont.add(liItem);// 菜单条menuBar.add(fileMenu);menuBar.add(systemMenu);// 框体添加文件区和菜单条frame.add(pane);frame.setJMenuBar(menuBar);//初始化字体center.setFont(font=new Font("宋体",0,12)); }/*** 构造器*/public Notepad() {initMainFrame();initComponent();}/*** 主函数** @param args*/public static void main(String[] args) {new Notepad().show();}/*** 自动换行方法*/private void autoChangeLine() {if (judge) { //judge为真即需要自动换行center.setLineWrap(true);} else { //judge为假不需要自动换行center.setLineWrap(false);}}/*** 文件另存的方法*/private void saveAs() {int option = chooser.showSaveDialog(frame); //调出文件保存选择器if (option == JFileChooser.APPROVE_OPTION) {currentFile= chooser.getSelectedFile();FileOutputStream fos = null;int op = 0;try {if (!currentFile.exists()) { // 文件不存在,则新建一个文件currentFile.createNewFile();fos = new FileOutputStream(currentFile);// 写入文件String content = center.getText();fos.write(content.getBytes());// 刷新缓存fos.flush();} else { // 文件存在if (!currentFile.canWrite()) { //文件为只读类型JOptionPane.showMessageDialog(frame, "此文件是只读类型,不允许写入!");} else { //文件不是只读类型op = JOptionPane.showConfirmDialog(frame,"文件已经存在,是否要覆盖?", "确认?",JOptionPane.YES_NO_CANCEL_OPTION);}if (op == JOptionPane.YES_OPTION) {//用户选择覆盖时,用输出流保存文件// 建立输出流fos = new FileOutputStream(currentFile);// 写入文件String content = center.getText();fos.write(content.getBytes());// 刷新缓存fos.flush();}}} catch (IOException e) {e.printStackTrace();} finally {// 关闭流if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}}}/*** 文件保存的方法*/private void save() {if (currentFile == null) {// 新建的文件saveAs(); //另存} else {// 已存在的文件if (!currentFile.canWrite()) { //文件为只读JOptionPane.showMessageDialog(frame, "此文件是只读类型,不允许写入!");saveAs(); //另存} else { //文件不为只读,用输出流保存文件FileOutputStream fos = null;try {// 建立输出流fos = new FileOutputStream(currentFile);// 写入文件String content = center.getText();fos.write(content.getBytes());// 刷新缓存fos.flush();} catch (IOException e1) {e1.printStackTrace();} finally {// 关闭流if (fos != null) {try {fos.close();} catch (IOException e1) {e1.printStackTrace();}}}}}}/*** 文件未改变时打开的方法*/private void open() {int option = chooser.showOpenDialog(frame); //调出文件选择器if (option == JFileChooser.APPROVE_OPTION) {currentFile = chooser.getSelectedFile(); //获得选择的文件txtName = chooser.getName(currentFile); //获得选择文件的名字frame.setTitle(txtName + "-记事本"); //在frame上显示文件名字的标题FileReader fi = null; //用字符输入流来显示文件的内容try {fi = new FileReader(currentFile);String sum = "";char[] buff = new char[400];int count = -1;while ((count = fi.read(buff)) != -1) {String once = new String(buff, 0, count);sum += once;}center.setText(sum);} catch (FileNotFoundException e1) {e1.printStackTrace();} catch (IOException e1) {e1.printStackTrace();} finally {try {fi.close();} catch (IOException e1) {e1.printStackTrace();}}}}/*** 文件未改变时新建的方法*/private void newTxt() {currentFile = null; //设置当前文件为空txtName = "无标题"; //当前文件名为“无标题”frame.setTitle(txtName + "-记事本");center.setText(null); //将文本区置空}/*** 判断文件是否改变** @return*/@SuppressWarnings("null")private boolean judge() {boolean judgeTxt = false;// 默认为假,文件没有改变if (currentFile == null) {// 文件不存在,即文件是新建的时候if (!compareTxt.equals("")) { // 文本区有字符串存在时,即文件已经改变judgeTxt = true;}} else {// 文件已经存在,用原来文件的内容和当前显示的内容做比较,如果相同则文件没有改变,如果不同,则文件改变了String sum = null;String compare = null;compare += center.getText();//获得文本区内容FileReader fi = null; //用字符流得到原来文件的内容try {fi = new FileReader(currentFile);char[] buff = new char[400];int count = -1;while ((count = fi.read(buff)) != -1) {String once = new String(buff, 0, count);sum += once;}} catch (FileNotFoundException e1) {e1.printStackTrace();} catch (IOException e1) {e1.printStackTrace();} finally {try {fi.close();} catch (IOException e1) {e1.printStackTrace();}}if (!compare.equals(sum)) {//原文件内容与当前文本区内容不同judgeTxt = true;}}return judgeTxt;}public void windowActivated(WindowEvent e) {}public void windowClosed(WindowEvent e) {}public void windowClosing(WindowEvent e) {//关闭按钮的监听compareTxt = center.getText(); //获得文本区内容if (judge()) { //文件内容已经改变了int option = JOptionPane.showConfirmDialog(frame,"文件内容已经改变,是否要保存文件?", "记事本",JOptionPane.YES_NO_CANCEL_OPTION);if (option == JOptionPane.YES_OPTION) {// 选择了是save();System.exit(0);} else if (option == JOptionPane.NO_OPTION) {// 选择了否System.exit(0);}} else {//文本区内容没有改变System.exit(0);}}public void windowDeactivated(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowOpened(WindowEvent e) {}public void actionPerformed(ActionEvent e) {Object source = e.getSource();if (source == newItem) {// 选择了新建compareTxt = center.getText();//获得文本区内容if (judge()) {// 文件内容已经被改变int option = JOptionPane.showConfirmDialog(frame,"文件内容已经改变,是否要保存文件?", "记事本",JOptionPane.YES_NO_CANCEL_OPTION);if (option == JOptionPane.YES_OPTION) {// 选择了是save();newTxt();} else if (option == JOptionPane.NO_OPTION) {// 选择了否newTxt();}} else {// 文件内容未改变newTxt();}} else if (source == openItem) {// 选择了打开compareTxt = center.getText();//获得文本区内容if (judge()) {// 文件内容已经被改变int option = JOptionPane.showConfirmDialog(frame,"文件内容已经改变,是否要保存文件?", "记事本",JOptionPane.YES_NO_CANCEL_OPTION);if (option == JOptionPane.YES_OPTION) {// 选择了是save(); // 另存open(); // 打开} else if (option == JOptionPane.NO_OPTION) {// 选择了否open(); // 打开}} else {// 文件内容未改变open();}} else if (source == saveItem) {// 选择的保存save();} else if (source == saveAsItem) {// 选择了另存saveAs();} else if (source == exitItem) {// 选择了退出compareTxt = center.getText();//获得文本区内容if (judge()) { // 文件内容已经改变int option = JOptionPane.showConfirmDialog(frame,"文件内容已经改变,是否要保存文件?", "记事本",JOptionPane.YES_NO_CANCEL_OPTION);if (option == JOptionPane.YES_OPTION) {// 选择了是save();System.exit(0);} else if (option == JOptionPane.NO_OPTION) {// 选择了否System.exit(0);}} else { // 文件内容没有改变System.exit(0);}}else if (source == larger) {font=center.getFont();fontSize=font.getSize();fontName=font.getName();fontSize++;font=new Font(fontName,0,fontSize);center.setFont(font);} else if (source == smaller) {font=center.getFont();fontSize=font.getSize();fontName=font.getName();fontSize--;font=new Font(fontName,0,fontSize);center.setFont(font);} else if (source == about) {JOptionPane.showMessageDialog(frame, "version:1.0\n"+ " 谢谢您的使用!\n" + "2011年8月3日");}else if(source==songItem){center.setFont(font=new Font("宋体",0,12));}else if(source==kaiItem){fontSize=font.getSize();font=new Font("楷体",0,fontSize);center.setFont(font);}else if(source==heiItem){fontSize=font.getSize();font=new Font("黑体",0,fontSize);center.setFont(font);}else if(source==liItem){fontSize=font.getSize();font=new Font("隶书",0,fontSize);center.setFont(font);}}// 自动换行按钮的监听事件public void itemStateChanged(ItemEvent e) {judge = !judge;autoChangeLine();}}。

android实现记事本app

android实现记事本app

android实现记事本app⾃⼰写的⼀个简单的记事本app,效果如下:⼀、⾸先是第⼀个界⾯的编写,最上⾯是⼀个TextView,中间是⼀个Linearlayout中嵌套⼀个listview布局,最下⾯是⼀个button。

下⾯附上第⼀个页⾯的简单布局xml⽂件。

<LinearLayout xmlns:android="/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="@android:color/darker_gray"android:orientation="vertical" ><TextViewandroid: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"/><LinearLayoutandroid:layout_width="fill_parent"android:id="@+id/listview"android:layout_margin="5dp"android:background="#81966F"android:layout_width="match_parent"android:layout_height="wrap_content" ></ListView></LinearLayout><Buttonandroid: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样式。

Android利用Intent实现记事本功能(NotePad)

Android利用Intent实现记事本功能(NotePad)

Android利⽤Intent实现记事本功能(NotePad)本⽂实例为⼤家分享了Intent如何实现⼀个简单的记事本功能的演⽰过程,供⼤家参考,具体内容如下1、运⾏截图单击右上⾓【…】会弹出【添加】菜单项,长按某条记录会弹出快捷菜单【删除】项。

2、主要设计步骤(1)添加引⽤⿏标右击【引⽤】à【添加引⽤】,在弹出的窗⼝中勾选“System.Data”和“System.Data.SQlite”,如下图所⽰:注意:不需要通过NuGet添加SQLite程序包,只需要按这种⽅式添加即可。

(2)添加图⽚到Android SDK API 23的Samples的NotePad例⼦下找到app_notes.png,将其添加到该项⽬中,并将其换名为ch12_app_notes.png。

<?xml version="1.0" encoding="utf-8"?><view xmlns:android="/apk/res/android"class="MyDemos.SrcDemos.ch1205LinedEditText"android:id="@+id/note"android:layout_width="match_parent"android:layout_height="match_parent"android:padding="5dip"android:scrollbars="vertical"android:fadingEdge="vertical"android:gravity="top"android:textSize="22sp"android:capitalize="sentences" />(4)添加ch1205_Main.axml⽂件<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="/apk/res/android" android:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:background="#ffffff"android:padding="10px"><ImageViewandroid:id="@+id/icon"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/ch12_app_notes" /><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:orientation="vertical"android:paddingTop="6px"><TextViewandroid:id="@+id/body"android:layout_width="wrap_content"android:layout_height="wrap_content" /><TextViewandroid:id="@+id/modified"android:layout_width="wrap_content"android:layout_height="wrap_content" /></LinearLayout></LinearLayout>(5)添加ch1205Note.cs⽂件using System;namespace MyDemos.SrcDemos{class ch1205Note : ng.Object{public long Id { get; set; }public string Body { get; set; }public DateTime ModifiedTime { get; set; }public ch1205Note(){Id = -1L;Body = string.Empty;}public ch1205Note(long id, string body, DateTime modified){Id = id;Body = body;ModifiedTime = modified;}public override string ToString(){return ModifiedTime.ToString();}}}using Android.Content;using Android.Runtime;using Android.Widget;using Android.Graphics;using Android.Util;namespace MyDemos.SrcDemos{[Register("MyDemos.SrcDemos.ch1205LinedEditText")]class ch1205LinedEditText : EditText{private Rect rect;private Paint paint;// 为了LayoutInflater需要提供此构造函数public ch1205LinedEditText(Context context, IAttributeSet attrs): base(context, attrs){rect = new Rect();paint = new Paint();paint.SetStyle(Android.Graphics.Paint.Style.Stroke);paint.Color = Color.LightGray;}protected override void OnDraw(Canvas canvas){int count = LineCount;for (int i = 0; i < count; i++){int baseline = GetLineBounds(i, rect);canvas.DrawLine(rect.Left, baseline + 1, rect.Right, baseline + 1, paint);}base.OnDraw(canvas);}}}(7)添加ch1205NoteRepository.cs⽂件using System;using System.Collections.Generic;using Mono.Data.Sqlite;namespace MyDemos.SrcDemos{class ch1205NoteRepository{private static string db_file = "notes.db3";private static SqliteConnection GetConnection(){var dbPath = bine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), db_file);bool exists = System.IO.File.Exists(dbPath);if (!exists) SqliteConnection.CreateFile(dbPath);var conn = new SqliteConnection("Data Source=" + dbPath);if (!exists) CreateDatabase(conn);return conn;}private static void CreateDatabase(SqliteConnection connection){var sql = "CREATE TABLE ITEMS (Id INTEGER PRIMARY KEY AUTOINCREMENT, Body ntext, Modified datetime);"; connection.Open();using (var cmd = connection.CreateCommand()){mandText = sql;cmd.ExecuteNonQuery();}// Create a sample note to get the user startedsql = "INSERT INTO ITEMS (Body, Modified) VALUES (@Body, @Modified);";using (var cmd = connection.CreateCommand()){mandText = sql;cmd.Parameters.AddWithValue("@Body", "今天有个约会");cmd.Parameters.AddWithValue("@Modified", DateTime.Now);cmd.ExecuteNonQuery();}connection.Close();}public static IEnumerable<ch1205Note> GetAllNotes(){var sql = "SELECT * FROM ITEMS;";using (var conn = GetConnection()){conn.Open();using (var cmd = conn.CreateCommand()){mandText = sql;using (var reader = cmd.ExecuteReader()){while (reader.Read()){yield return new ch1205Note(reader.GetInt32(0),reader.GetString(1),reader.GetDateTime(2));}}}}}public static ch1205Note GetNote(long id){var sql = "SELECT * FROM ITEMS WHERE Id = id;";using (var conn = GetConnection()){conn.Open();using (var cmd = conn.CreateCommand()){mandText = sql;using (var reader = cmd.ExecuteReader()){if (reader.Read())return new ch1205Note(reader.GetInt32(0), reader.GetString(1), reader.GetDateTime(2)); elsereturn null;}}}}public static void DeleteNote(ch1205Note note){var sql = string.Format("DELETE FROM ITEMS WHERE Id = {0};", note.Id);using (var conn = GetConnection()){conn.Open();using (var cmd = conn.CreateCommand()){mandText = sql;cmd.ExecuteNonQuery();}}}public static void SaveNote(ch1205Note note){using (var conn = GetConnection()){conn.Open();using (var cmd = conn.CreateCommand()){if (note.Id < 0){// Do an insertmandText = "INSERT INTO ITEMS (Body, Modified) VALUES (@Body, @Modified); SELECT last_insert_rowid();"; cmd.Parameters.AddWithValue("@Body", note.Body);cmd.Parameters.AddWithValue("@Modified", DateTime.Now);note.Id = (long)cmd.ExecuteScalar();}else{// Do an updatemandText = "UPDATE ITEMS SET Body = @Body, Modified = @Modified WHERE Id = @Id";cmd.Parameters.AddWithValue("@Id", note.Id);cmd.Parameters.AddWithValue("@Body", note.Body);cmd.Parameters.AddWithValue("@Modified", DateTime.Now);cmd.ExecuteNonQuery();}}}}}}(8)添加ch1205NoteAdapter.cs⽂件using Android.App;using Android.Content;using Android.Widget;namespace MyDemos.SrcDemos{class ch1205NoteAdapter : ArrayAdapter{private Activity activity;public ch1205NoteAdapter(Activity activity, Context context, int textViewResourceId, ch1205Note[] objects): base(context, textViewResourceId, objects){this.activity = activity;}public override Android.Views.View GetView(int position, Android.Views.View convertView, Android.Views.ViewGroup parent){//Get our object for this positionvar item = (ch1205Note)GetItem(position);// 如果convertView不为null则重⽤它,否则从当前布局中填充(inflate)它。

记事本程序源代码汇总

记事本程序源代码汇总

记事本程序源代码汇总下面是一个简单的记事本程序的源代码:```#include <iostream>#include <fstream>#include <string>using namespace std;void showMencout << "**********************" << endl; cout << " 记事本程序 " << endl; cout << "**********************" << endl; cout << "请选择以下操作:" << endl;cout << "1. 新建记事本文件" << endl;cout << "2. 打开已有记事本文件" << endl; cout << "3. 查看记事本文件内容" << endl; cout << "4. 添加文本到记事本文件" << endl; cout << "5. 退出程序" << endl;cout << "**********************" << endl; void createFilstring filename;cout << "请输入新建记事本文件的文件名:";cin >> filename;//在当前目录创建一个新文件ofstream outFile(filename);outFile.close(;cout << "成功创建记事本文件:" << filename << endl; void openFilstring filename;cout << "请输入要打开的记事本文件的文件名:";cin >> filename;//尝试打开已存在的文件ifstream inFile(filename);if (!inFile)cout << "无法打开文件:" << filename << endl;} elsestring content;getline(inFile, content, '\0');cout << "记事本文件内容:" << endl;cout << content << endl;inFile.close(;}void viewFilstring filename;cout << "请输入要查看的记事本文件的文件名:"; cin >> filename;//尝试打开已存在的文件ifstream inFile(filename);if (!inFile)cout << "无法打开文件:" << filename << endl; } elsestring line;cout << "记事本文件内容:" << endl;while (getline(inFile, line))cout << line << endl;}inFile.close(;}void appendToFilstring filename;cout << "请输入要添加文本的记事本文件的文件名:";cin >> filename;//尝试打开已存在的文件ofstream outFile(filename, ios::app);if (!outFile)cout << "无法打开文件:" << filename << endl;} elsestring content;cout << "请输入要添加的文本内容(以#结束):" << endl; while (true)getline(cin, content);if (content == "#")break;}outFile << content << endl;}outFile.close(;cout << "成功添加文本到记事本文件:" << filename << endl; }int maiint choice;doshowMenu(;cout << "请输入您的选择:";cin >> choice;switch (choice)case 1:createFile(;break;case 2:openFile(;break;case 3:viewFile(;break;case 4:appendToFile(;break;case 5:cout << "感谢使用记事本程序,再见!" << endl;break;default:cout << "无效的选择,请重新输入!" << endl;}} while (choice != 5);return 0;```这个记事本程序通过命令行界面提供了以下操作:1.新建记事本文件:用户输入一个文件名后,在当前目录下创建一个新文件作为记事本。

记事本代码

记事本代码

package com.sgf.notepad;import android.app.ListActivity;import android.content.Intent;import android.database.Cursor;import android.os.Bundle;import android.util.Log;import android.view.ContextMenu;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.ContextMenu.ContextMenuInfo;import android.widget.AdapterView;import android.widget.ListView;import android.widget.SimpleCursorAdapter;/*** @author mapeijie*/public class DummyNote extends ListActivity {private int mNoteNumber = 1;protected static final int MENU_INSERT = Menu.FIRST;protected static final int MENU_DELETE = Menu.FIRST+1;protected static final int MENU_MODIFY = Menu.FIRST+1;private static final int ACTIVITY_EDIT = 0x1001;private NotesDbAdapter dbHelper;private Cursor cursor;/*** 应用的入口程序*/@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.main);getListView().setEmptyView(findViewById(R.id.empty));registerForContextMenu(getListView());setAdapter();}/*** 获取要显示数据源*/private void setAdapter() {dbHelper = new NotesDbAdapter(this);dbHelper.open();fillData();}/*** 填充数据*/private void fillData() {cursor = dbHelper.getall();startManagingCursor(cursor);String[] from = new String[]{"note"};int[] to = new int[]{android.R.id.text1};SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,yout.simple_list_item_1,cursor,from,to);setListAdapter(adapter);}/*** 长按HOME 键显示两个菜单添加备忘删除备忘*/@Overridepublic boolean onCreateOptionsMenu(Menu menu) {menu.add(0,MENU_INSERT,0,R.string.addNote);menu.add(0,MENU_DELETE,0,R.string.delNote);return super.onCreateOptionsMenu(menu);}/*** 对HOME键产生的菜单的选中事件*/@Overridepublic boolean onOptionsItemSelected(MenuItem item) {switch(item.getItemId()) {case MENU_INSERT:String noteName = "Note " + mNoteNumber++;dbHelper.create(noteName);fillData();case MENU_DELETE:dbHelper.delete(getListView().getSelectedItemId());fillData();}return super.onOptionsItemSelected(item);}/*** 当选中ListView 中的一个View 时的动作* 在这里作为编辑备忘的入口*/@Overrideprotected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id);Intent intent = new Intent(this, NoteEdit.class);intent.putExtra(NotesDbAdapter.KEY_ROWID, id);startActivityForResult(intent, ACTIVITY_EDIT);}/*** startActivityForResult() 和onActivityResult() 相伴而生* 前者启动并进入另外一个activity 后者处理从另外一个activity 回来的事件*/@Overrideprotected void onActivityResult(int requestCode, int resultCode,Intent intent) {super.onActivityResult(requestCode, resultCode, intent);fillData();System.out.println("DummyNote Activity ---------------- onActivityResult");}/*** 创建长按菜单点击一个菜单1秒钟不松开即可创建一个右键菜单*/@Overridepublic void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {menu.add(0, MENU_DELETE, 0, "删除日志");menu.setHeaderTitle("要怎么处理这个项目!!!");super.onCreateContextMenu(menu, v, menuInfo);}/*** 长按菜单的选中事件*/@Overridepublic boolean onContextItemSelected(MenuItem item) {AdapterView.AdapterContextMenuInfo info;info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();switch (item.getItemId()) {case MENU_DELETE :Log.d("MENU", "item"+info.id) ;dbHelper.delete(info.id) ;fillData() ;break ;}return super.onContextItemSelected(item);}}package com.sgf.notepad;import android.app.Activity;import android.database.Cursor;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;/*** @author mapeijie*/public class NoteEdit extends Activity {private NotesDbAdapter dbHelper;private EditText field_note;private Button button_confirm;private Long rowId;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);dbHelper = new NotesDbAdapter(this);dbHelper.open();setContentView(yout.note_edit);//编辑的时候使用另一个UIfindViews();showAndUpdateNote(savedInstanceState);}private void findViews() {field_note = (EditText) findViewById(R.id.note);button_confirm = (Button) findViewById(R.id.confirm);}/*** 编辑修改备忘并且保存* @param savedInstanceState*/private void showAndUpdateNote(Bundle savedInstanceState) {if (rowId == null) {Bundle extras = getIntent().getExtras();rowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID) : null;}showNote();button_confirm.setOnClickListener(new View.OnClickListener() {public void onClick(View view) {dbHelper.update(rowId, field_note.getText().toString());setResult(RESULT_OK);finish();}});}/*** 填充要编辑的备忘*/private void showNote() {if (rowId != null) {Cursor note = dbHelper.get(rowId);startManagingCursor(note);field_note.setText(note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_NOTE)));}}}package com.sgf.notepad;import java.util.Date;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;/*** 数据库操作接口* @author mapeijie*/public class NotesDbAdapter {private static final String DA TABASE_NAME = "notes.db";private static final int DA TABASE_VERSION = 1;private static final String DA TABASE_TABLE = "notes";public static final String KEY_ROWID = "_id";public static final String KEY_NOTE = "note";public static final String KEY_CREATED = "created";private Context context = null;private DatabaseHelper dbHelper;private SQLiteDatabase db;String[] strCols = new String[] { KEY_ROWID, KEY_NOTE, KEY_CREATED };private static final String DA TABASE_CREATE ="create table "+DA TABASE_TABLE+"("+ "_id INTEGER PRIMARY KEY,"+ "note TEXT,"+ "created INTEGER,"+ "modified INTEGER"+ ");";public NotesDbAdapter(Context ctx) {this.context = ctx;}public NotesDbAdapter open() throws SQLException {dbHelper = new DatabaseHelper(context);db = dbHelper.getWritableDatabase();return this;}public void close() {dbHelper.close();}// add an entrypublic long create(String Note) {Date now = new Date();ContentValues args = new ContentValues();args.put(KEY_NOTE, Note);args.put(KEY_CREATED, now.getTime());return db.insert(DATABASE_TABLE, null, args);}// remove an entrypublic boolean delete(long rowId) {return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;}// query single entrypublic Cursor get(long rowId) throws SQLException {Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NOTE, KEY_CREATED }, KEY_ROWID + "=" + rowId,null, null, null, null, null);if (mCursor != null) {mCursor.moveToFirst();}return mCursor;}// get all entriespublic Cursor getall() {return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NOTE,KEY_CREATED }, null, null, null, null, null);}// updatepublic boolean update(long rowId, String note) {ContentValues args = new ContentValues();args.put(KEY_NOTE, note);return db.update(DA TABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;}//初始化数据库连接时做一些动作private static class DatabaseHelper extends SQLiteOpenHelper {public DatabaseHelper(Context context) {super(context, DATABASE_NAME, null,DA TABASE_VERSION);}//Called when the database is created for the first time.@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(DATABASE_CREATE);}//Called when the database needs to be upgraded.@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {db.execSQL("DROP TABLE IF EXISTS " +DA TABASE_TABLE);onCreate(db);}//Close any open database object.@Overridepublic synchronized void close() {super.close();}//Create and/or open a database.@Overridepublic synchronized SQLiteDatabase getReadableDatabase() {return super.getReadableDatabase();}//Create and/or open a database that will be used for reading and writing.@Overridepublic synchronized SQLiteDatabase getWritableDatabase() {return super.getWritableDatabase();}//Called when the database has been opened.@Overridepublic void onOpen(SQLiteDatabase db) {super.onOpen(db);}}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1、MainActivity01.package cn.dccssq;02.03.import android.app.ListActivity;04.import android.content.Intent;05.import android.database.Cursor;06.import android.os.Bundle;07.import android.util.Log;08.import android.view.Menu;09.import android.view.MenuItem;10.import android.view.View;11.import android.widget.ListAdapter;12.import android.widget.ListView;13.import android.widget.SimpleCursorAdapter;14.15.public class MainActivity extends ListActivity {16.17. private static final int INSERT_ID = Menu.FIRST;18.19. private static final int DELETE_ID = Menu.FIRST + 1;20.21. private static final int ACTIVITY_CREATE = 0;22.23. private static final int ACTIVITY_EDIT = 1;24.25. private DiaryDbAdapter diaryDb;26.27. private Cursor cursor;28. /** Called when the activity is first created. */29. @Override30. public void onCreate(Bundle savedInstanceState) {31. super.onCreate(savedInstanceState);32. setContentView(yout.main);33.34. diaryDb =new DiaryDbAdapter(this);35. diaryDb.open();36.37. }38.39. private void showListView(){40. cursor = diaryDb.getAllNotes();41.42. String[] from = new String[]{DiaryDbAdapter.KEY_TITLE,DiaryDbAdapter.KEY_BODY};43. int[] to = new int[]{R.id.text1,R.id.created};44.45. ListAdapter cursorAdapter = new SimpleCursorAdapter(this,yout.diary_row,cursor,from,to);46. setListAdapter(cursorAdapter);47. }48.49. @Override50. protected void onListItemClick(ListView l, View v, int position, long id) {51. // TODO Auto-generated method stub52. super.onListItemClick(l, v, position, id);53. Cursor c = cursor;54. c.move(position);55. Intent intent = new Intent(this,ActivityDiary.class);56. intent.putExtra(DiaryDbAdapter.KEY_ROWID, id);57. intent.putExtra(DiaryDbAdapter.KEY_TITLE, c.getString(c58. .getColumnIndexOrThrow(DiaryDbAdapter.KEY_TITLE)));59. intent.putExtra(DiaryDbAdapter.KEY_BODY, c.getString(c60. .getColumnIndexOrThrow(DiaryDbAdapter.KEY_BODY)));61. startActivityForResult(intent, ACTIVITY_EDIT);62. }63.64. @Override65. protected void onActivityResult(int requestCode, int resultCode, Intent data) {66. // TODO Auto-generated method stub67. super.onActivityResult(requestCode, resultCode, data);68. showListView();69. }70.71. @Override72. public boolean onCreateOptionsMenu(Menu menu) {73. // TODO Auto-generated method stub74. super.onCreateOptionsMenu(menu);75. menu.add(0,INSERT_ID,0,R.string.menu_insert);76. menu.add(0,DELETE_ID,0,R.string.menu_delete);77. return true;78. }79.80. @Override81. public boolean onMenuItemSelected(int featureId, MenuItem item) {82. // TODO Auto-generated method stub83. switch(item.getItemId()){84. case INSERT_ID:85. Log.i(&quot;INSERT:&quot;, String.valueOf(INSERT_ID));86. createDiary();87. return true;88. case DELETE_ID:89. Log.i(&quot;DELETE_ID:&quot;, String.valueOf(getListView().getSelectedItemId()));90. diaryDb.deleteDiary(getListView().getSelectedItemId());91. showListView();92. return true;93. }94. return super.onMenuItemSelected(featureId, item);95. }96.97. private void createDiary(){98.99. Intent intent = new Intent();100. intent.setClass(this, ActivityDiary.class);101. startActivityForResult(intent, ACTIVITY_CREATE);102. }103.}2、ActivityDiary01.package cn.dccssq;02.03.import android.app.Activity;04.import android.content.Intent;05.import android.os.Bundle;06.import android.util.Log;07.import android.view.View;08.import android.widget.Button;09.import android.widget.EditText;10.11.public class ActivityDiary extends Activity {12.13. // title EditText14. EditText titleTxt;15. // body EditText16. EditText bodyTxt;17. // save Button18. Button btn;19. // Row Id20. Long rowId;21. private DiaryDbAdapter diaryDb;22.23. @Override24. protected void onCreate(Bundle savedInstanceState) {25. // TODO Auto-generated method stub26. super.onCreate(savedInstanceState);27. setContentView(yout.notepad);28.29. // Initialize the DiaryDbAdapter.30. diaryDb = new DiaryDbAdapter(this);31.32. // Get the screen control33. titleTxt = (EditText)findViewById(R.id.title);34. bodyTxt = (EditText)findViewById(R.id.body_text);35. btn = (Button)findViewById(R.id.button);36. rowId = null ;37.38. // Get data from the front page39. Bundle bundle = getIntent().getExtras();40.41. if(bundle!=null){42. Log.i(&quot;bund:&quot;,bundle.toString());43.44. // Set data to page45. String title = bundle.getString(DiaryDbAdapter.KEY_TITLE);46. String body = bundle.getString(DiaryDbAdapter.KEY_BODY);47. rowId = bundle.getLong(DiaryDbAdapter.KEY_ROWID);48. if(title!=null)49. {50. titleTxt.setText(title);51. }52. if(body!=null)53. {54. bodyTxt.setText(body);55. }56.}57.58. btn.setOnClickListener(new View.OnClickListener() {59.60. public void onClick(View arg0) {61. // TODO Auto-generated method stub62. String title = titleTxt.getText().toString();63. String body = bodyTxt.getText().toString();64. if(checkInput(title, body)){65. diaryDb.open();66. if(rowId!=null){67. diaryDb.updateDiary(rowId, title, body);68. }else{69. diaryDb.createDiary(title, body);70. }71. diaryDb.close();72.73. Intent mIntent = new Intent();74. setResult(RESULT_OK, mIntent);75.76. finish();77. }78. }79. });80. }81.82. /**83. * Validate the input.84. * @param title85. * @param body86. * @return87. */88. public boolean checkInput(String title ,String body){89.90. if(null==title || title.trim().length()==0){91. titleTxt.setError(&quot;Please input the title!&quot;);92. return false;93. }94.95. if(null==body || body.trim().length()==0){96. bodyTxt.setError(&quot;Please input the content!&quot;);97. return false;99. return true;100. }101.}3、DiaryDbAdapter DB操作类,提供了两种增删查改的功能代码01.package cn.dccssq;02.03.import java.util.Calendar;04.05.import android.content.ContentValues;06.import android.content.Context;07.import android.database.Cursor;08.import android.database.SQLException;09.import android.database.sqlite.SQLiteDatabase;10.import android.database.sqlite.SQLiteException;11.12.public class DiaryDbAdapter {13. public static final String KEY_TITLE = &quot;title&quot;;14. public static final String KEY_BODY = &quot;body&quot;;15. public static final String KEY_ROWID = &quot;_id&quot;;16. public static final String KEY_CREATED = &quot;created&quot;;17.18. private DatabaseHelper databaseHelper;19.20. private Context context;21.22. private SQLiteDatabase sqliteDatabase;23.24. public DiaryDbAdapter(Context context) {25. this.context = context;26. }27.28. /**29. * Open the Database30. */31. public void open(){32. databaseHelper = new DatabaseHelper(context);33.35. {36. sqliteDatabase = databaseHelper.getWritableDatabase();37. }catch(SQLiteException e){38. sqliteDatabase = databaseHelper.getReadableDatabase();39.}40. }41.42. /**43. * Close the Database44. */45. public void close()46. {47. sqliteDatabase.close();48. }49.50. /**51. * Insert the Data52. * @param title53. * @param body54. * @return55. */56. public long createDiary(String title,String body){57.58. ContentValues content = new ContentValues();59. content.put(KEY_TITLE, title);60. content.put(KEY_BODY, body);61. Calendar calendar = Calendar.getInstance();62. String created = calendar.get(Calendar.YEAR) + &quot;/&quot;63. + calendar.get(Calendar.MONTH) + &quot;/&quot;64. + calendar.get(Calendar.DAY_OF_MONTH) + &quot; &quot;65. + calendar.get(Calendar.HOUR_OF_DAY) + &quot;:&quot;66. + calendar.get(Calendar.MINUTE);67. content.put(KEY_CREATED, created);68.69. return sqliteDatabase.insert(databaseHelper.DATABSE_TABLE, null, content);70. }71.72. /**73. * Delete the record74. * @param rowId75. * @return76. */77. public boolean deleteDiary(long rowId){78.79. String whereString = KEY_ROWID + &quot;=&quot; + rowId;80. return sqliteDatabase.delete(databaseHelper.DATABSE_TABLE, whereString, null)&gt;0;81. }82.83. /**84. * Get all Records85. * @return86. */87. public Cursor getAllNotes()88. {89. String[] searchResult = {KEY_ROWID, KEY_TITLE,KEY_BODY, KEY_CREATED};90. return sqliteDatabase.query(databaseHelper.DATABSE_TABLE, searchResult, null, null, null, null, null);91. }92.93. /**94. * Get the record by condition95. * @param rowId96. * @return97. * @throws SQLException98. */99. public Cursor getDiary(long rowId) throws SQLException{100.101. String[] searchResult = {KEY_ROWID, KEY_TITLE,KEY_BODY, KEY_CREATED}; 102. String whereString = KEY_ROWID + &quot;=&quot; + rowId;103.104. Cursor mCursor = sqliteDatabase.query(true, databaseHelper.DATABSE_TABLE, searchResult, whereString, null, null, null, null, null);105. if(mCursor!=null){106. mCursor.moveToFirst();107. }108. return mCursor;109. }110.111. public boolean updateDiary(long rowId ,String title,String body){112.113. ContentValues values = new ContentValues();114. values.put(KEY_ROWID, title);115. values.put(KEY_BODY,body);116.117. Calendar calendar = Calendar.getInstance();118. String created = calendar.get(Calendar.YEAR) + &quot;/&quot;119. + calendar.get(Calendar.MONTH) + &quot;/&quot;120. + calendar.get(Calendar.DAY_OF_MONTH) + &quot; &quot;121. + calendar.get(Calendar.HOUR_OF_DAY) + &quot;:&quot;122. + calendar.get(Calendar.MINUTE);123. values.put(KEY_CREATED, created);124. String whereString = KEY_ROWID + &quot;=&quot; + rowId;125.126. return sqliteDatabase.update(databaseHelper.DATABSE_TABLE, values, whereString, null)&gt;0;127. }128.129. public void xinjianDiary(String title,String body){130.131. Calendar calendar = Calendar.getInstance();132. String created = calendar.get(Calendar.YEAR) + &quot;/&quot;133. + calendar.get(Calendar.MONTH) + &quot;/&quot;134. + calendar.get(Calendar.DAY_OF_MONTH) + &quot; &quot;135. + calendar.get(Calendar.HOUR_OF_DAY) + &quot;:&quot;136. + calendar.get(Calendar.MINUTE);137.138. String insertSQL = &quot;INSERT INTO &quot; + databaseHelper.DATABSE_TABLE139. +&quot;(&quot; + KEY_ROWID +&quot;,&quot; + KEY_TITLE+&quot;,&quot; + KEY_BODY +&quot;,&quot; + KEY_CREATED + &quot;)&quot;140. + &quot; values (?,?,?,?)&quot; ;141. Object[] args = {null,title,body,created};142. sqliteDatabase.execSQL(insertSQL, args);143. }144.145. public void bianjiDiary(long rowId ,String title,String body){146. Calendar calendar = Calendar.getInstance();147. String created = calendar.get(Calendar.YEAR) + &quot;/&quot;148. + calendar.get(Calendar.MONTH) + &quot;/&quot;149. + calendar.get(Calendar.DAY_OF_MONTH) + &quot; &quot;150. + calendar.get(Calendar.HOUR_OF_DAY) + &quot;:&quot;151. + calendar.get(Calendar.MINUTE);152.153. String updateSQL = &quot;update &quot; + databaseHelper.DATABSE_TABLE 154. +&quot; set &quot; + KEY_TITLE+&quot;=? ,&quot; + KEY_BODY+&quot;=? ,&quot; + KEY_CREATED + &quot;=? &quot;155. + &quot; where &quot; + KEY_ROWID + &quot;= ?&quot; ;156. Object[] args = {title,body,created,rowId};157. sqliteDatabase.execSQL(updateSQL, args);158. }159.160. public void shanchuDiary(long rowId ){161. String deleteSQL = &quot;delete from &quot;+ databaseHelper.DATABSE_TABLE +&quot; where &quot; + KEY_ROWID + &quot;= ?&quot; ; 162. Object[] args = {rowId};163. sqliteDatabase.execSQL(deleteSQL, args);164. }165.166. public Cursor qudeAllNotes()167. {168. String searchSQL = &quot;select _id , title , body ,created from &quot;+ databaseHelper.DATABSE_TABLE;169. return sqliteDatabase.rawQuery(searchSQL, null);170. }171.}4、DatabaseHelper01.package cn.dccssq;02.03.import android.content.Context;04.import android.database.sqlite.SQLiteDatabase;05.import android.database.sqlite.SQLiteOpenHelper;06.07.public class DatabaseHelper extends SQLiteOpenHelper {08.09. private final static String DATABSE_NAME = &quot;notepad&quot;;10. private final static int DATABASE_VERSION = 1;11. public final static String DATABSE_TABLE = &quot;diary&quot;;12.。

相关文档
最新文档