安卓记事本程序源代码

合集下载

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”,想必大家已经明白是怎么回事了吧。

  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.。

相关文档
最新文档