当前位置: 网学 > 编程文档 > Android > 正文

Android高手进阶教程

来源:Http://myeducs.cn 联系QQ:点击这里给我发消息 作者: myeducs.cn 发布时间: 13/03/17

【网学网提醒】:以下是网学会员为您推荐的Android高手进阶教程,希望本篇文章对您学习有所帮助。


    Android高手进阶教程一)-------Android常用名令集锦高手进阶教程(一
    大家好,今天我们要讲的是android开发中,比较常用的名令集锦,在我们开发中难免用到Android命令,有些确实命令确实很有用处。特别对于一些初学者来说,命令根本没有想过用也不会用,比如他们想安装一个.apk文件到模拟器上面,但是他们不会启动模拟器,他们只会先启动Eclipse,然后在启动模拟器,这样不但浪费时间,而且Eclipse又占用你的内存。这也是我为什么总结这篇文章的原因了,希望对大家有所帮助。如果想让系统认识你输入的命令(如:输入android命令)有两种方法:1.设置环境变量.(和设置java路径一样,具体网上查哦!);2.直接进入你SDK里tools目录(cd:sdkpath/tools)这样也OK.不过在此建议使用第一种!下面就是自己的小小总结:1.android:对你只要输入android就会出来,SDKandAVDmanager我们可以更新SDK,增删修改AVD.效果如下图:
    2.androidlistavds:这条命令将会列出所有我们创建的android模拟器.效果如下图:
     3.androidlisttargets:这条命令是列出我们所有的SDK可用版本,效果如下图:
    4.adbdevices:这条命令是列出所有装载的设置,效果如下图(一个是模拟器,一个是真机):
    5.adbshell:这条命令是进入设备根目录/,取得对设备的控制权,如输入ls命令等。
     6.adbinstallXXX.apk.这条命令是安装apk文件,如果你有多个设备(而你想把apk安装到emulator-5554这个模拟器上)则要输入:adbinstall-semulator-5554D:/XXX.apk.7.emulator-avdavdname这条命令将启动一个模拟器,初学者学会这条,就不用下次启动模拟器的时候还要打开Eclipse了。用法如下:
    8.mksdcard256Md:\sdcard.img对于模拟器当然要创建sdcard了,这条命令是将在D盘下生成256M的sdcard.9.adbpull/adbpush.我们创建完sdcard以后,要向里面放东西,或者把里面的东西弄出来,就用到以上命令了。以adbpush(将sdcard外的东西存放进去.)为例,用法如下:adbpushfoo.txt/sdcard/foo.txt10.androidcreateavd--nameAndroid2.0--target5这是创建avd的命令。--name后面就是avd的名称,target是SDK的版本。这条语句是创建名称为Android2.0并且版本为5的avd.创建完可以用androidlistavds。查看是否已经创建成功。11.ctrl+F11键的使用当我们启动模拟器的时候,通常是port模式,如果我们想在land下看效果,这个组合按钮就用到啦.看一下效果图:
     Android高手进阶教程二)之----AndroidLauncher抽屉类高手进阶教程(二之SlidingDrawer的使用
    最近在研究Lanucher,看了源码,发现了SlidingDrawer这个类,也就是所谓的"抽屉"类。它的用法很简单,要
    包括handle,和content.handle就是当你点击它的时候,content要么抽抽屉要么关抽屉。别的不多说了,具体步骤如下.1.新建Android工程,命名为SlidingDrawer.2.准备素材,在这里我的图标是用Launcher2里面的图标,放在drawable-hdpi
     文件夹目录结构如下:
    3.设置main.xml布局:代码如下:viewplaincopytoclipboardprint?     />     android:layout_height="fill_parent"android:background="#00ff00">4.设置handle图标的样式,在drawable里添加handle.xml,代码如下:viewplaincopytoclipboardprint?    _enabled="true"android:drawable="@drawable/handle_normal"/>
     5.运行之。将会得到如下效果:
    的比较简单呵呵,如果想深入了解,大家看Launcher源码吧!
     Android高手进阶教程三)之----Android中自定义View的高手进阶教程(三之应用
    大家好我们今天的教程是在Android教程中自定义View的学习,对于初学着来说,他们习惯了Android传统的页面布局方式,如下代码:viewplaincopytoclipboardprint?当然上面的布局方式可以帮助我们完成简单应用的开发了,但是如果你想写一个复杂的应用,这样就有点牵强了,大家不信可以下源码都研究看看,高手写的布局方式,如上面的布局高手通常是这样写的:viewplaincopytoclipboardprint?
     viewplaincopytoclipboardprint?其中AextendsLinerLayout,BextendsTextView.其中AextendsLinerLayout,BextendsTextView.为了帮助大家更容易理解,我写了一个简单的Demo,具体步骤如下:首先新建一个Android工程命名为ViewDemo.然后自定义一个View类,命名为MyView(extendsView).代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.content.Context;importandroid.graphics.Canvas;importandroid.graphics.Color;importandroid.graphics.Paint;importandroid.graphics.Rect;importandroid.graphics.Paint.Style;importandroid.util.AttributeSet;importandroid.view.View;publicclassMyViewextendsVie
    w{privatePaintmPaint;privateContextmContext;privatestaticfinalStringmString="WelcometoMrWei'sblog";publicMyView(Contextcontext){super(context);}publicMyView(Contextcontext,AttributeSetattr){super(context,attr);}@OverrideprotectedvoidonDraw(Canvascanvas){//TODOAuto-generatedmethodstubsuper.onDraw(canvas);mPaint=newPaint();//设置画笔颜色mPaint.setColor(Color.RED);//设置填充mPaint.setStyle(Style.FILL);
     //画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标canvas.drawRect(newRect(10,10,100,100),mPaint);mPaint.setColor(Color.BLUE);//绘制文字canvas.drawText(mString,10,110,mPaint);}}packagecom.android.tutor;importandroid.content.Context;importandroid.graphics.Canvas;importandroid.graphics.Color;importandroid.graphics.Paint;importandroid.graphics.Rect;importandroid.graphics.Paint.Style;importandroid.util.AttributeSet;importandroid.view.View;publicclassMyViewextendsView{privatePaintmPaint;privateContextmContext;privatestaticfinalStringmString="WelcometoMrWei'sblog";publicMyView(Contextcontext){super(context);}publicMyView(Contextcontext,AttributeSetattr){super(context,attr);}@OverrideprotectedvoidonDraw(Canvascanvas){//TODOAuto-generatedmethodstubsuper.onDraw(canvas);mPaint=newPaint();//设置画笔颜色mPaint.setColor(Color.RED);//设置填充mPaint.setStyle(Style.FILL);
     //画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标canvas.drawRect(newRect(10,10,100,100),mPaint);mPaint.setColor(Color.BLUE);//绘制文字canvas.drawText(mString,10,110,mPaint);}}然后将我们自定义的View加入到main.xml布局文件中,代码如下:viewplaincopytoclipboardprint?
     最后执行之,效果如下图:
    OK,大功告成,今天就写到这里
    Android高手进阶教程四)之----Android中自定义属性手进阶教程(四之(attr.xml,TypedArray)的使用的使用
    今天我们的教程是根据前面一节扩展进行的,如果你没有看,请
    点击Android高手进阶教程(三)查看第三课,这样跟容易方便你的理解!在xml文件里定义控件的属性,我们已经习惯了android:attrs="",那么我们能不能定义自己的属性能,比如:test:attrs=""呢?答案是肯定的.好了我就不卖关子了,直接进入主题。大致以下步骤:一、在res/values文件下定义一个attrs.xml文件.代码如下:viewplaincopytoclipboardprint?一、在res/values文件下定义一个attrs.xml文件.代码如下:
    
一、在res/values文件下定义一个attrs.xml文件.代码如下:二、我们在MyView.java代码修改如下,其中下面的构造方法是重点,我们获取定义的属性我们R.sytleable.MyView_textColor,获取方法中后面通常设定默认值(floattextSize=a.getDimension(R.styleable.MyView_textSize,36);),防止我们在xml文件中没有定义.从而使用默认值!获取,MyView就是定义在里的名字,获取里面属性用名字_属性连接起来就可以.TypedArray通常最后调用.recycle()方法,为了保持以后使用该属性一致性!viewplaincopytoclipboardprint?publicMyView(Contextcontext,AttributeSetattrs){super(context,attrs);mPaint=newPaint();TypedArraya=context.obtainStyledAttributes(attrs,R.styleable.MyView);inttextColor=a.getColor(R.styleable.MyView_textColor,0XFFFFFFFF);floattextSize=a.getDimension(R.styleable.MyView_textSize,36);mPaint.setTextSize(textSize);mPaint.setColor(textColor);a.recycle();}publicMyView(Contextcontext,AttributeSetattrs){super(context,attrs);mPaint=newPaint();
     TypedArraya=context.obtainStyledAttributes(attrs,R.styleable.MyView);inttextColor=a.getColor(R.styleable.MyView_textColor,0XFFFFFFFF);floattextSize=a.getDimension(R.styleable.MyView_textSize,36);mPaint.setTextSize(textSize);mPaint.setColor(textColor);a.recycle();}MyView.java全部代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.content.Context;importandroid.content.res.TypedArray;importandroid.graphics.Canvas;importandroid.graphics.Color;importandroid.graphics.Paint;importandroid.graphics.Rect;importandroid.graphics.Paint.Style;importandroid.util.AttributeSet;importandroid.view.View;publicclassMyViewextendsView{privatePaintmPaint;privateContextmContext;privatestaticfinalStringmString="WelcometoMrWei'sblog";publicMyView(Contextcontext){super(context);mPaint=newPaint();}pu
    blicMyView(Contextcontext,AttributeSetattrs){super(context,attrs);mPaint=newPaint();TypedArraya=context.obtainStyledAttributes(attrs,R.styleable.MyView);inttextColor=a.getColor(R.styleable.MyView_textColor,0XFFFFFFFF);floattextSize=a.getDimension(R.styleable.MyView_textSize,
     36);mPaint.setTextSize(textSize);mPaint.setColor(textColor);a.recycle();}@OverrideprotectedvoidonDraw(Canvascanvas){//TODOAuto-generatedmethodstubsuper.onDraw(canvas);//设置填充mPaint.setStyle(Style.FILL);//画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标canvas.drawRect(newRect(10,10,100,100),mPaint);mPaint.setColor(Color.BLUE);//绘制文字canvas.drawText(mString,10,110,mPaint);}}packagecom.android.tutor;importandroid.content.Context;importandroid.content.res.TypedArray;importandroid.graphics.Canvas;importandroid.graphics.Color;importandroid.graphics.Paint;importandroid.graphics.Rect;importandroid.graphics.Paint.Style;importandroid.util.AttributeSet;importandroid.view.View;publicclassMyViewextendsView{privatePaintmPaint;privateContextmContext;privatestaticfinalStringmString="WelcometoMrWei'sblog";publicMyView(Contextcontext){super(context);mPaint=newPaint();}publicMyView(Contextcontext,AttributeSetattrs){super(context,attrs);
     mPaint=newPaint();TypedArraya=context.obtainStyledAttributes(attrs,R.styleable.MyView);inttextColor=a.getColor(R.styleable.MyView_textColor,0XFFFFFFFF);floattextSize=a.getDimension(R.styleable.MyView_textSize,36);mPaint.setTextSize(textSize);mPaint.setColor(textColor);a.recycle();}@OverrideprotectedvoidonDraw(Canvascanvas){//TODOAuto-generatedmethodstubsuper.onDraw(canvas);//设置填充mPaint.setStyle(Style.FILL);//画一个矩形,前俩个是矩形左上角坐标,后面俩个是右下角坐标canvas.drawRect(newRect(10,10,100,100),mPaint);mPaint.setColor(Color.BLUE);//绘制文字canvas.drawText(mString,10,110,mPaint);}}三、将我们自定义的MyView加入布局main.xml文件中,平且使用自定义属性,自定义属性必须加上:xmlns:test="schemas.android/apk/res/com.android.tutor"蓝色是自定义属性的前缀,红色是我们包名.main.xml全部代码如下:viewplaincopytoclipboardprint?     android:layout_width="fill_parent"android:layout_height="fill_parent">    d="schemas.android/apk/res/android"xmlns:test="schemas.android/apk/res/com.android.tutor"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent">
     四、运行之效果如下图:
    今天就到此结束
    高手进阶教程(----AndroidAndroid高手进阶教程(五)之----Android中LayoutInflater的使用大家好我们这一节讲的是LayoutInflater的使用,在实际开发种LayoutInflater这个类还是非常有用的,它的作用类似于findViewById(),不同点是LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体widget控件(如:Button,TextView等)。为了让大家容易理解我做了一个简单的Demo,主布局main.xml里有一个TextView和一个Button,当点击Button,出现Dialog,而这个Dialog的布局方式是我们在layout目录下定义的custom_dialog.xml文件(里面左右分布,左边ImageView,右边TextView)。
     效果图如下:
    下面我将详细的说明Demo的实现过程:1、新建一个Android工程,我们命名为LayoutInflaterDemo.2、修改main.xml布局,里面主要在原来基础上增加了一个Button.代码如下:viewplaincopytoclipboardprint?     android:text="ShowCustomDialog"/>3.定义对话框的布局方式,我们在layout目录下,新建一个名为custom_dialog.xml文件具体代码如下:viewplaincopytoclipboardprint?     android:textColor="#FFF"/>4.修改主程序LayouInflaterDemo.java代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.app.Activity;importandroid.app.AlertDialog;importandroid.content.Context;importandroid.os.Bundle;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.ImageView;importandroid.widget.TextView;publicclassLayoutInflaterDemoextendsActivityimplementsOnClickListener{privateButtonbutton;publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
     button=(Button)findViewById(R.id.button);button.setOnClickListener(this);}@OverridepublicvoidonClick(Viewv){showCustomDialog();}publicvoidshowCustomDialog(){AlertDialog.Builderbuilder;AlertDialogalertDialog;ContextmContext=LayoutInflaterDemo.this;//下面俩种方法都可以////LayoutInflaterinflater=getLayoutInflater();LayoutInflaterinflater=(LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);Viewlayout=inflater.inflate(R.layout.custom_dialog,null);TextViewtext=(TextView)layout.findViewById(R.id.text);text.setText("Hello,WelcometoMrWei'sblog!");ImageViewimage=(ImageView)layout.findViewById(R.id.image);image.setImageResource(R.drawable.icon);builder=newAlertDialog.Builder(mContext);builder.setView(layout);alertDialog=builder.create();alertDialog.show();}}packagecom.android.tutor;importandroid.app.Activity;importandroid.app.AlertDialog;importandroid.content.Context;importandroid.os.Bundle;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.ImageView;importandroid.widget.TextView;
     publicclassLayoutInflaterDemoextendsActivityimplementsOnClickListener{privateButtonbutton;publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);button=(Button)findViewById(R.id.button);button.setOnClickListener(this);}@OverridepublicvoidonClick(Viewv){showCustomD
    ialog();}publicvoidshowCustomDialog(){AlertDialog.Builderbuilder;AlertDialogalertDialog;ContextmContext=LayoutInflaterDemo.this;//下面俩种方法都可以////LayoutInflaterinflater=getLayoutInflater();LayoutInflaterinflater=(LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);Viewlayout=inflater.inflate(R.layout.custom_dialog,null);TextViewtext=(TextView)layout.findViewById(R.id.text);text.setText("Hello,WelcometoMrWei'sblog!");ImageViewimage=(ImageView)layout.findViewById(R.id.image);image.setImageResource(R.drawable.icon);builder=newAlertDialog.Builder(mContext);builder.setView(layout);alertDialog=builder.create();alertDialog.show();}}5、最后执行之,点击Button,将得到上述效果。
     Android高手进阶教程(六)之----Android中MenuInflater的使用(布局定义菜单)!大家好,我们上一节讲的是LayoutInflater的使用,而这一节我将讲一下MenuInflater,顾名思义,LayoutInflater是用来解析定义在layout下的布局文件,那么MenuInflater是不是用来解析定义在menu目录下的菜单布局文件呢?恭喜你答对了!(*^__^*)嘻嘻……我们传统意义上的定义菜单感觉比较繁琐,当我们使用MenuInflater来生成菜单,你会发现是多么的爽朗,呵呵,我今天的小Demo,是定义四个菜单,并且实现了一个菜单事件。就是我们点击设置(Setting)菜单,进入手机设置状态!下面看一下效果图:
     下面是实现Demo的详细步骤:一、建立一个Android工程我们命名为MenuInflaterDemo.二、在res目录下创建menu目录,并且创建options_menu.xml(我们定义的菜单)文件,代码如下:viewplaincopytoclipboardprint?     /> 三、主类MenuInflaterDemo.java的编码,这里写的代
    码很少哦,我这里只写了第四个菜单(Settings)的响应事件.全部代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.Menu;importandroid.view.MenuInflater;importandroid.view.MenuItem;publicclassMenuInflaterDemoextendsActivity{@Override
     publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);}@OverridepublicbooleanonCreateOptionsMenu(Menumenu){MenuInflaterinflater=getMenuInflater();inflater.inflate(R.menu.options_menu,menu);returntrue;}@OverridepublicbooleanonOptionsItemSelected(MenuItemitem){switch(item.getItemId()){caseR.id.menu_add:break;caseR.id.menu_wallaper:break;caseR.id.menu_search:break;caseR.id.menu_setting:showSettings();break;}returnsuper.onOptionsItemSelected(item);}
    privatevoidshowSettings(){finalIntentsettings=Intent(android.provider.Settings.ACTION_SETTINGS);settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);startActivity(settings);}}packagecom.android.tutor;importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;new
     importandroid.view.Menu;importandroid.view.MenuInflater;importandroid.view.MenuItem;publicclassMenuInflaterDemoextendsActivity{@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);}@OverridepublicbooleanonCreateOptionsMenu(Menumenu){MenuInflaterinflater=getMenuInflater();inflater.inflate(R.menu.options_menu,menu);returntrue;}@OverridepublicbooleanonOptionsItemSelected(MenuItemitem){switch(item.getItemId()){caseR.id.menu_add:break;caseR.id.menu_wallaper:break;caseR.id.menu_search:break;caseR.id.menu_setting:showSettings();break;}returnsuper.onOptionsItemSelected(item);}
    privatevoidshowSettings(){finalIntentsettings=Intent(android.provider.Settings.ACTION_SETTINGS);settings.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);startActivity(settings);}new
     }四、运行代码之,点击模拟器上的menu按钮将会出现上述效果图!
    高手进阶教程(----Android的使用!Android高手进阶教程(七)之----Android中Preferences的使用!大家好,我们这一节讲的是AndroidPreferences的学习,Preferences在Android当中被用来记录应用,以及用户喜好等等,它可以用来保存简单的数据类型,如Int,Double,Boolean等。Preferences中保存的数据可以理解为Map型。我们通过PreferenceManager以及getDefaultSharedPreferences(Context)来获取它,比如当我们想获得整数我们可以用getInt(Stringkey,intdefVal).获取里面的某个键值,当我们想修改时候我们用putInt(Stringkey,intnewVal),最后用edit(
    ),方法提交!千万不要忘记了哦~为了让大家跟好的理解我做了一个简单的Demo,程序主要有个TextView控件,上面写着用户使用改应用的次数。效果如下图所示:
    下面是实现Demo的大体步骤:一、新建一个Android工程命名为:PreferencesDemo。二、在修改main.xml布局文件,这里只是在TextView控件里加了一个id.代码如下:viewplaincopytoclipboardprint?
     三、修改PreferenceDemo.java的代码,全部代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.app.Activity;importandroid.content.SharedPreferences;importandroid.os.Bundle;importandroid.preference.PreferenceManager;importandroid.widget.TextView;publicclassPreferencesDemoextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
     SharedPreferencesmPerferences=PreferenceManager.getDefaultSharedPreferences(this);intcounter=mPerferences.getInt("counter",0);TextViewmTextView=(TextView)findViewById(R.id.text);mTextView.setText("Thisapphasbeenstarted"+counter+"times.");SharedPreferences.EditormEditor=mPerferences.edit();mEditor.putInt("counter",++counter);mEditormit();}}packagecom.android.tutor;importandroid.app.Activity;importandroid.content.SharedPreferences;importandroid.os.Bundle;importandroid.preference.PreferenceManager;importandroid.widget.TextView;publicclassPreferencesDemoextendsActivity{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
    SharedPreferencesmPerferences=PreferenceManager.getDefaultSharedPreferences(this);intcounter=mPerferences.getInt("counter",0);TextViewmTextView=(TextView)findViewById(R.id.text);mTextView.setText("Thisapphasbeenstarted"+counter+"times.");SharedPreferences.EditormEditor=mPerferences.edit();mEditor.putInt("counter",++counter);
     mEditormit();}}四、运行代码,实现上述效果.五、查看Preferences文件,首先打开命令终
    端:adbshell一下,然后cddata/data进入该目录,ls一下我们会发现一大堆包文件,入下图所示:
    cdcom.android.tutor(这里是我程序的包名)/shared_prefs,ls一下会发现.xml文件如下图:
    打开.xml文件,格式如下(为什么这样大家自己去理解):viewplaincopytoclipboardprint?
     高手进阶教程(----Android开发案例(世界杯倒计时!)Android高手进阶教程(八)之----AndroidWidget开发案例(世界杯倒计时!)今天我们要写一下AndroidWidget的开发,由于快点凌晨,我就不说的太具体了,同志们就模仿吧!首先看一下效果图:
    下面是Demo的详细步骤:一、新建一个Android工程命名为:WidgetDemo.
     二、准备素材,一个是Widget的图标,一个是Widget的背景。存放目录如下图:
    三、修改string.xml文件如下:viewplaincopytoclipboardprint?HelloWorld,WidetDemo!DaysToWorldCupHelloWorld,WidetDemo!DaysToWorldCup四、建立Widget内容提供者文件,我们在res下建立xml文件夹,并且新建一个widget_provider.xml代码入下:viewplaincopytoclipboardprint?     />五、修改main.xml布局,代码如下:viewplaincopytoclipboardprint?
     六、修改WidgetDemo.java代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importjava.util.Calendar;importjava.util.Date;importjava.util.GregorianCalendar;importjava.util.Timer;importjava.util.TimerTask;importandroid.appwidget.AppWidgetManager;importandroid.appwidget.AppWidgetProvider;importandroid.content.ComponentName;importandroid.content.Context;importandroid.widget.RemoteViews;publicclassWidetDemoextendsAppWidgetProvider{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonUpdate(ContextappWidgetManager,int[]appWidgetIds){Timertimer=newTimer();timer.scheduleAtFixedRate(newMyTime(context,appWidgetManager),1,60000);super.onUpdate(context,appWidgetManager,appWidgetIds);}
    context,
    AppWidgetManager
    privateclassMyTimeextendsTimerTask{RemoteViewsremoteViews;AppWidgetManagerappWidgetManager;ComponentNamethisWidget;publicMyTime(Contextcontext,AppWidgetManagerappWidgetManager){this.appWidgetManager=appWidgetManager;remoteViews=newRemoteViews(context.getPackageName(),R.layout.main);thisWidgetComponentName(context,WidetDemo.class);}=new
     publicvoidrun(){Datedate=newDate();Calendarcalendar=newGregorianCalendar(2010,06,11);longdays=(((calendar.getTimeInMillis()-date.getTime())/1000))/86400;remoteViews.setTextViewText(R.id.wordcup,"距离南非世界杯还有"+days+"天");appWidgetManager.updateAppWidget(thisWidget,remoteViews);}}}packagecom.android.tutor;importjava.util.Calendar;importjava.util.Date;importjava.util.GregorianCalendar;importjava.util.Timer;importjava.util.TimerTask;importandroid.appwidget.AppWidgetManager;importandroid.appwidget.AppWidgetProvider;importandroid.content.ComponentName;importandroid.content.Context;importandroid.widget.RemoteViews;publicclassWidetDemoextendsAppWidgetProvider{/**Calledwhentheactivityisfirstcreated.*/@OverridepublicvoidonUpdate(Contextcontext,AppWidgetManagerappWidgetManager,int[]appWidgetIds){Timertimer=newTimer();timer.scheduleAtFixedRate(newMyTime(context,appWidgetManager),1,60000);super.onUpdate(context,appWidgetManager,appWidgetIds);}
    privateclassMyTimeextendsTimerTask{RemoteViewsremoteViews;AppWidgetManagerappWidgetManager;
     ComponentNamethisWidget;publicMyTime(Contextcontext,AppWidgetManagerappWidgetManager){this.appWidgetManager=appWidgetManager;remoteViews=newRemoteViews(context.getPackageName(),R.layout.main);thisWidget=newComponentName(context,WidetDemo.class);}publicvoidrun(){Datedate=newDate();Calendarcalendar=newGregorianCalendar(2010,06,11);longdays=(((calendar.getTimeInMillis()-date.getTime())/1000))/86400;remoteViews.setTextViewText(R.id.wordcup,"距离南非世界杯还有"+days+"天");appWidgetManager.updateAppWidget(thisWidget,remoteViews);}}}七、修改配置文件AndroidManifest.xml,代码如下:viewplaincop
    ytoclipboardprint?
     八、点击运行(Ctrl+F11),之,运行成功后,我们长时间点击桌面,会出现如下俩个,依次点击,就可以看到最上面的效果图:
     Android高手进阶教程九)之----AndroidHandler的使用高手进阶教程(九之
    大家好我们这一节讲的是AndroidHandler的使用,在讲Handler之前,我们先提个小问题,就是如何让程序5秒钟更新一下Title.首先我们看一下习惯了Java编程的人,在不知道Handler的用法之前是怎么样写的程序,代码如下所示:viewplaincopytoclipboardprint?packagecom.android.tutor;importjava.util.Timer;importjava.util.TimerTask;
     importandroid.app.Activity;importandroid.os.Bundle;publicclassHandlerDemoextendsActivity{//title为setTitle方法提供变量,这里为了方便我设置成了int型privateinttitle=0;publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);Timertimer=newTimer();timer.scheduleAtFixedRate(newMyTask(),1,5000);}privateclassMyTaskextendsTimerTask{@Overridepublicvoidrun(){setTitle("WelcometoMrWei'sblog"+title);title++;}}}packagecom.android.tutor;importjava.util.Timer;importjava.util.TimerTask;importandroid.app.Activity;importandroid.os.Bundle;publicclassHandlerDemoextendsActivity{//title为setTitle方法提供变量,这里为了方便我设置成了int型privateinttitle=0;publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);Timertimer=newTimer();timer.scheduleAtFixedRate(newMyTask(),1,5000);}privateclassMyTaskextendsTimerTask{@Override
     publicvoidrun(){setTitle("
    WelcometoMrWei'sblog"+title);title++;}}}然而当我们执行程序,并不能达到我们预期的效果,所以Android引进了Handler这个特殊的类,可以说它是Runnable和Activity交互的桥梁,所以我们只要在run方法中发送Message,而在Handler里,通过不同的Message执行不同的任务。所以我们修改后的代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importjava.util.Timer;importjava.util.TimerTask;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;publicclassHandlerDemoextendsActivity{//title为setTitle方法提供变量,这里为了方便我设置成了int型privateinttitle=0;privateHandlermHandler=newHandler(){publicvoidhandleMessage(Messagemsg){switch(msg.what){case1:updateTitle();break;}};};publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);Timertimer=newTimer();timer.scheduleAtFixedRate(newMyTask(),1,5000);}privateclassMyTaskextendsTimerTask{
     @Overridepublicvoidrun(){Messagemessage=newMessage();message.what=1;mHandler.sendMessage(message);}}
    publicvoidupdateTitle(){setTitle("WelcometoMrWei'sblog"+title);title++;}}packagecom.android.tutor;importjava.util.Timer;importjava.util.TimerTask;importandroid.app.Activity;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;publicclassHandlerDemoextendsActivity{//title为setTitle方法提供变量,这里为了方便我设置成了int型privateinttitle=0;privateHandlermHandler=newHandler(){publicvoidhandleMessage(Messagemsg){switch(msg.what){case1:updateTitle();break;}};};publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);Timertimer=newTimer();
     timer.scheduleAtFixedRate(newMyTask(),1,5000);}privateclassMyTaskextendsTimerTask{@Overridepublicvoidrun(){Messagemessage=newMessage();message.what=1;mHandler.sendMessage(message);}}
    publicvoidupdateTitle(){setTitle("WelcometoMrWei'sblog"+title);title++;}}下面我们看一下效果图:
     高手进阶教程(----AndroidAndroid高手进阶教程(十)之----AndroidPopupWindow的使用大家好,我们这一节讲的是AndroidPopupWindow的使用!在我理解其实PopupWindow其实类似于一个不能动的Widget(仅从显示效果来说!)它是浮在别的窗口之上的.下面我将给大家做一个简单的Demo,类似于音乐播放器的Widget的效果,点击Button的时候出来PopupWindow,首先我们看一下效果图:
     下面是核心代码:viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.app.Activity;importandroid.content.Context;importandroid.os.Bundle;importandroid.view.Gravity;importandroid.view.Layou
    tInflater;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.view.ViewGroup.LayoutParams;importandroid.widget.Button;importandroid.widget.PopupWindow;publicclassPopupWindowDemoextendsOnClickListener{privateButtonbtn;
    Activity
    implements
    publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);
     btn=(Button)findViewById(R.id.btn);btn.setOnClickListener(this);}@OverridepublicvoidonClick(Viewv){ContextmContext=PopupWindowDemo.this;if(v.getId()==R.id.btn){LayoutInflatermLayoutInflater=(LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);Viewmusic_popunwindwow=mLayoutInflater.inflate(R.layout.music_popwindow,null);PopupWindowmPopupWindow=newPopupWindow(music_popunwindwow,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);mPopupWindow.showAtLocation(findViewById(R.id.main),Gravity.RIGHT|Gravity.BOTTOM,0,0);}}}packagecom.android.tutor;importandroid.app.Activity;importandroid.content.Context;importandroid.os.Bundle;importandroid.view.Gravity;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.view.ViewGroup.LayoutParams;importandroid.widget.Button;importandroid.widget.PopupWindow;publicclassPopupWindowDemoextendsActivityimplementsOnClickListener{privateButtonbtn;publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);btn=(Button)findViewById(R.id.btn);btn.setOnClickListener(this);}
     @OverridepublicvoidonClick(Viewv){ContextmContext=PopupWindowDemo.this;if(v.getId()==R.id.btn){LayoutInflatermLayoutInflater=(LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);Viewmusic_popunwindwow=mLayoutInflater.inflate(R.layout.music_popwindow,null);PopupWindowmPopupWindow=newPopupWindow(music_popunwindwow,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);mPopupWindow.showAtLocation(findViewById(R.id.main),Gravity.RIGHT|Gravity.BOTTOM,0,0);}}}
    需要强调的是这里PopupWindow必须有某个事件触发才会显示出来,不然总会抱错,不信大家可以试试!随着这个问题的出现,就会同学问了,那么我想初始化让PopupWindow显示出来,那怎么办了,不去寄托于其他点击事件,在这里我用了定时器Timer来实现这样的效果,当然这里就要用到Handler了,如果大家不理解的可以返回Android高手进阶教程(九)之----AndroidHandler的使用!!看一看,加深了解:下面是核心代码:viewplaincopytoclipboardprint?packagecom.android.tutor;importjava.util.Timer;importjava.util.TimerTask;importandroid.app.Activity;importandroid.content.Context;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.view.Gravity;importandroid.view.LayoutInflater;
    importandroid.view.View;importandroid.view.ViewGroup.LayoutParams;importandroid.widget.PopupWindow;publicclassPopupWindowDemoextendsActivity{privateHandlermHandler=newHandler(){
     publicvoidhandleMessage(Messagemsg){switch(msg.what){case1:showPopupWindow();break;}};};publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);//createthetimerTimertimer=newTimer();timer.schedule(newinitPopupWindow(),100);}privateclassinitPopupWindowextendsTimerTask{@Overridepublicvoidrun(){Messagemessage=newMessage();message.what=1;mHandler.sendMessage(message);}}
    publicvoidshowPopupWindow(){ContextmContext=PopupWindowDemo.this;LayoutInflatermLayoutInflater=(LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);Viewmusic_popunwindwow=mLayoutInflater.inflate(R.layout.music_popwindow,null);PopupWindowmPopupWindow=newPopupWindow(music_popunwindwow,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);mPopupWindow.showAtLocation(findViewById(R.id.main),Gravity.CENTER,0,0);}
     }packagecom.android.tutor;importjava.util.Timer;importjava.util.TimerTask;importandroid.app.Activity;importandroid.content.Context;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.view.Gravity;importandroid.view.LayoutInflater;importandroid.view.View;importandroid.view.ViewGroup.LayoutParams;importandroid.widget.PopupWindow;publicclassPopupWindowDemoextendsActivity{privateHandlermHandler=newHandler(){publicvoidhandleMessage(Messagemsg){switch(msg.what){case1:showPopupWindow();break;}};};publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);//createthetimerTimertimer=newTimer();timer.schedule(newinitPopupWindow(),100);}privateclassinitPopupWindowextendsTimerTask{@Overridepublicvoidrun(){Messagemessage=newMessage();message.what=1;mHandler.sendMessage(message);}
     }
    publicvoidshowPopupWindow(){ContextmContext=PopupWindowDemo.this;LayoutInflatermLayoutInflater=(LayoutInflater)mContext.getSystemService(LAYOUT_INFLATER_SERVICE);Viewmusic_popunwindwow=mLayoutInflater.inflate(R.layout.music_popwindow,null);PopupWindowmPopupWindow=newPopupWindow(music_popunwindwow,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);mPopupWindow.showAtLocation(findViewById(R.id.main),Gravity.CENTER,0,0);}}效果如下图:
     Android高手进阶教程十一之----Android通用获取Ip的方法判断手机是否联网的方法)高手进阶教程(十一十一)之(判断手机是否联网的方法)大家好,我们这一节讲一下,Android获取Ip的一些方法,在我们开发中,有判断手机是否联网,或者想获得当前手机的Ip地址,当然WIFI连接的和我们3G卡的Ip地址当然是不一样的.
    首先我尝试了如下方法:viewplaincopytoclipboardprint?WifiManagerwifiManager=(WifiManager)getSystemService(WIFI_SERVICE);WifiInfowifiInfo=wifiManager.getConnectionInfo();intipAddress=wifiInfo.getIpAddress();WifiManagerwifiManager=(WifiManager)getSystemService(WIFI_SERVICE);WifiInfowifiInfo=wifiManager.getConnectionInfo();intipAddress=wifiInfo.getIpAddress();但是获得的居然是一个整数,我尝试了用些数学方法都没有成功!,所以这种方法不可取!最后查了一些资料,发现如下方法是比较通用的,我尝试了WIFI和G3卡,都获取了争取的Ip地址:代码如下:viewplaincopytoclipboardprint?publicStringgetLocalIpAddress(){try{for(Enumerationen=NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){NetworkInterfaceintf=en.nextElement();for(EnumerationenumIpAddr=intf.getInetAddresses();enumIpAddr.hasMoreElements();){InetAddressinetAddress=enumIpAddr.nextElement();if(!inetAddress.isLoopbackAddress()){returninetAddress.getHostAddress().toString();}}}}catch(SocketExceptionex){Log.e(LOG_TAG,ex.toString());}returnnull;}publicStringgetLocalIpAddress(){try{for(Enumerationen=NetworkInterface.getNetworkInterfaces();en.hasMoreElements();){NetworkInterfaceintf=en.nextElement();for(EnumerationenumIpAddr=intf.getInetAddresses();enumIpAddr.hasMoreElements();){
     InetAddressinetAddress=enumIpAddr.nextElement();if(!inetAddress.isLoopbackAddress()){returninetAddress.getHostAddress().toString();}}}}catch(SocketExceptionex){Log.e(LOG_TAG,ex.toString());}returnnull;}当我的手机处于飞行状态是,获得Ip地址为空,刚好符合要求!!!
    高手进阶教程(十二)----AndroidAndroid高手进阶教程(十二)之----Android在一个应用中如何启动另外一个已安装的应用今天晚上Jimmy问了我一个问题,就是如何在一个应用中通过某个事件,而去启动另外一个已安装的应用。所以愿意和大家分享一下!而为了能让大家更加容易的理解,我写了一个简单的Demo,我们的程序有俩个按钮,其中一个点击会启动我自己写的应用(一个3D应用为例),而另外一个按钮会启动系统自带的应用(如,日历,闹钟,计算器等等).这里我一日历为例子!首先看一下我们的效果图(点击第一个按钮为例):
     下面是Demo的详细步骤:一、新建一个Android工程命名为StartAnotherApplicationDemo.二、修改main.xml布局,代码如下:viewplaincopytoclipboardprint?    ext="WelcometoMrWei'sBlog."/>
     三、修改主程序StartAnotherApplicationDemo.java代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.app.Activity;importandroid.content.ComponentName;importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;publicclassStartAnotherApplicationDemoextendsActivity{
     privateButtonmButton01,mButton02;publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);mButton01=(Button)findViewById(R.id.button);mButton02=(Button)findViewById(R.id.start_calender);//-----启动我们自身写的程序-----------------mButton01.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){//-----核心部分-----前名一个参数是应用程序的包名,后一个是这个应用程序的主Activity名Intentintent=newIntent();intent.setComponent(newComponentName("com.droidnova.android.games.vortex","com.droidnova.android.games.vortex..Vortex"));startActivity(intent);}});//-----启动系统自带的应用程序-----------------mButton02.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){Intentintent=newIntent();intent.setComponent(newComponentName("com.android.calendar","com.android.calendar.LaunchActivity"));startActivity(intent);}});}}packagecom.android.tutor;importandroid.app.Activity;importandroid.content.ComponentName;importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.View;importandroid.widget.Button;publicclassStartAnotherApplicationDemoextendsActivity{privateButtonmButton01,mButton02;
     publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);mButton01=(Button)findViewById(R.id.button);mButton02=(Button)findViewById(R.id.start_calender);//-----启动我们自身写的程序-----------------mButton01.setOnClickListener(newButton.
    OnClickListener(){publicvoidonClick(Viewv){//-----核心部分-----前名一个参数是应用程序的包名,后一个是这个应用程序的主Activity名Intentintent=newIntent();intent.setComponent(newComponentName("com.droidnova.android.games.vortex","com.droidnova.android.games.vortex..Vortex"));startActivity(intent);}});//-----启动系统自带的应用程序-----------------mButton02.setOnClickListener(newButton.OnClickListener(){publicvoidonClick(Viewv){Intentintent=newIntent();intent.setComponent(newComponentName("com.android.calendar","com.android.calendar.LaunchActivity"));startActivity(intent);}});}}四、执行之,将得到如上效果!
    高手进阶教程(十三)----AndroidAndroid高手进阶教程(十三)之----Android数据库SQLiteDatabase的使用
     大家好,好久没有更新博客了,最近由于身体不适让大家久等了,好了,直接进入主题~Android提供了三种数据存储方式,第一种是文件存储;第二种是SharedPreferences存储;第三种就是数据库SQLiteDatabase存储。文件存储我就不用多说了,而SharedPreferences可以存取简单的数据(int,double,float.etc),它经常用于数据缓存,因为它读取存储简单。详细可以参见本系列。Android高手进阶教程(七)之----Android中Preferences的使用!今天我们将讲一下SQLiteDatabase的使用。而掌握SqliteDatabase,将会我们接下来掌握ContentProvider打下良好的基石。为了让大家更好的掌握,我们手把手完成该节的Demo。第一步:新建一个Android工程,命名为SQLiteDatabaseDemo.
    第二步:创建一个新的类BooksDB.java这个类要继承于android.database.sqlite.SQLiteOpenHelper抽象类,我们要实现其中两个方法:onCreate(),onUpdate.具体代码如下:
     viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.content.ContentValues;importandroid.content.Context;importandroid.database.Cursor;importandroid.database.sqlite.SQLiteDatabase;importandroid.database.sqlite.SQLiteOpenHelper;publicclassBooksDBextendsSQLiteOpenHelper{privatefinalstaticStringDATABASE_NAME="BOOKS.db";privatefinalstaticintDATABASE_VERSION=1;privatefinalstaticStringTABLE_NAME="books_table";publicfinalstaticStringBOOK_ID="book_id";publicfinalstaticStringBOOK_NAME="book_name";publicfinalstaticStringBOOK_AUTHOR="book_author";publicBooksDB(Contextcontext){//TODOAuto-generatedconstructorstubsuper(context,DATABASE_NAME,null,DATABASE_VERSION);}//创建table@OverridepublicvoidonCreate(SQLiteDatabasedb){Stringsql="CREATETABLE"+TABLE_NAME+"("+BOOK_ID+"INTEGERprimarykeyautoincrement,"+BOOK_NAME+"text,"+BOOK_AUTHOR+"text);";db.execSQL(sql);}@OverridepublicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){Stringsql="DROPTABLEIFEXISTS"+TABLE_NAME;
    db.execSQL(sql);onCreate(db);}publicCursorselect(){SQLiteDatabasedb=this.getReadableDatabase();Cursorcursor=db.query(TABLE_NAME,null,null,null,null,null,null);returncursor;}//增加操作publiclonginsert(Stringbookname,Stringauthor)
     {SQLiteDatabasedb=this.getWritableDatabase();/*ContentValues*/ContentValuescv=newContentValues();cv.put(BOOK_NAME,bookname);cv.put(BOOK_AUTHOR,author);longrow=db.insert(TABLE_NAME,null,cv);returnrow;}//删除操作publicvoiddelete(intid){SQLiteDatabasedb=this.getWritableDatabase();Stringwhere=BOOK_ID+"=?";String[]whereValue={Integer.toString(id)};db.delete(TABLE_NAME,where,whereValue);}//修改操作publicvoidupdate(intid,Stringbookname,Stringauthor){SQLiteDatabasedb=this.getWritableDatabase();Stringwhere=BOOK_ID+"=?";String[]whereValue={Integer.toString(id)};ContentValuescv=newContentValues();cv.put(BOOK_NAME,bookname);cv.put(BOOK_AUTHOR,author);db.update(TABLE_NAME,cv,where,whereValue);}}packagecom.android.tutor;importandroid.content.ContentValues;importandroid.content.Context;importandroid.database.Cursor;importandroid.database.sqlite.SQLiteDatabase;importandroid.database.sqlite.SQLiteOpenHelper;publicclassBooksDBextendsSQLiteOpenHelper{privatefinalstaticStringDATABASE_NAME="BOOKS.db";privatefinalstaticintDATABASE_VERSION=1;privatefinalstaticStringTABLE_NAME="books_table";publicfinalstaticStringBOOK_ID="book_id";publicfinalstaticStringBOOK_NAME="book_name";publicfinalstaticStringBOOK_AUTHOR="book_author";
     publicBooksDB(Contextcontext){//TODOAuto-generatedconstructorstubsuper(context,DATABASE_NAME,null,DATABASE_VERSION);}//创建table@OverridepublicvoidonCreate(SQLiteDatabasedb){Stringsql="CREATETABLE"+TABLE_NAME+"("+BOOK_ID+"INTEGERprimarykeyautoincrement,"+BOOK_NAME+"text,"+BOOK_AUTHOR+"text);";db.execSQL(sql);}@OverridepublicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){Stringsql="DROPTABLEIFEXISTS"+TABLE_NAME;db.execSQL(sql);onCreate(db);}publicCursorselect(){SQLiteDatabasedb=this.getReadableDatabase();Cursorcursor=db.query(TABLE_NAME,null,null,null,null,null,null);returncursor;}//增加操作publiclonginsert(Stringbookname,Stringauthor){SQLiteDatabasedb=this.getWritableDatabase();/*ContentValues*/ContentValuescv=newContentValues();cv.put(BOOK_NAME,bookname);cv.put(BOOK_AUTHOR,author);longrow=db.insert(TABLE_NAME,null,cv);returnrow;}//删除操作publicvoiddelete(intid){SQLiteDatabasedb=this.getWritableDatabase();Stringwhere=BOOK_ID+"=?";String[]whereValue={Integer.toString(id)};db.delete(TABLE_NAME,where,whereValue);
     }//修改操作publicvoidupdate(intid,Stringbookname,Stringauthor){SQLiteDatabasedb=this.getWritableDatabase();Stringwhere=BOOK
    _ID+"=?";String[]whereValue={Integer.toString(id)};ContentValuescv=newContentValues();cv.put(BOOK_NAME,bookname);cv.put(BOOK_AUTHOR,author);db.update(TABLE_NAME,cv,where,whereValue);}}
    第三步:修改main.xml布局如下,由两个EditText和一个ListView组成,代码如下:viewplaincopytoclipboardprint?
     第四步:修改SQLiteDatabaseDemo.java代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.app.Activity;importandroid.content.Context;importandroid.database.Cursor;importandroid.os.Bundle;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.AdapterView;importandroid.widget.BaseAdapter;importandroid.widget.EditText;importandroid.widget.ListView;importandroid.widget.TextView;
     importandroid.widget.Toast;publicclassSQLiteDatabaseDemoextendsActivityimplementsAdapterView.OnItemClickListener{privateBooksDBmBooksDB;privateCursormCursor;privateEditTextBookName;privateEditTextBookAuthor;privateListViewBooksList;privateintBOOK_ID=0;protectedfinalstaticintMENU_ADD=Menu.FIRST;protectedfinalstaticintMENU_DELETE=Menu.FIRST+1;protectedfinalstaticintMENU_UPDATE=Menu.FIRST+2;publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);setUpViews();}publicvoidsetUpViews(){mBooksDB=newBooksDB(this);mCursor=mBooksDB.select();BookName=(EditText)findViewById(R.id.bookname);BookAuthor=(EditText)findViewById(R.id.author);BooksList=(ListView)findViewById(R.id.bookslist);BooksList.setAdapter(newBooksListAdapter(this,mCursor));BooksList.setOnItemClickListener(this);}@Overridepublic
    booleanonCreateOptionsMenu(Menumenu){super.onCreateOptionsMenu(menu);menu.add(Menu.NONE,MENU_ADD,0,"ADD");menu.add(Menu.NONE,MENU_DELETE,0,"DELETE");menu.add(Menu.NONE,MENU_DELETE,0,"UPDATE");returntrue;}publicbooleanonOptionsItemSelected(MenuItemitem){
     super.onOptionsItemSelected(item);switch(item.getItemId()){caseMENU_ADD:add();break;caseMENU_DELETE:delete();break;caseMENU_UPDATE:update();break;}returntrue;}publicvoidadd(){Stringbookname=BookName.getText().toString();Stringauthor=BookAuthor.getText().toString();//书名和作者都不能为空,或者退出if(bookname.equals("")||author.equals("")){return;}mBooksDB.insert(bookname,author);mCursor.requery();BooksList.invalidateViews();BookName.setText("");BookAuthor.setText("");Toast.makeText(this,"AddSuccessed!",Toast.LENGTH_SHORT).show();}publicvoiddelete(){if(BOOK_ID==0){return;}mBooksDB.delete(BOOK_ID);mCursor.requery();BooksList.invalidateViews();BookName.setText("");BookAuthor.setText("");Toast.makeText(this,"DeleteSuccessed!",Toast.LENGTH_SHORT).show();}
     publicvoidupdate(){Stringbookname=BookName.getText().toString();Stringauthor=BookAuthor.getText().toString();//书名和作者都不能为空,或者退出if(bookname.equals("")||author.equals("")){return;}mBooksDB.update(BOOK_ID,bookname,author);mCursor.requery();BooksList.invalidateViews();BookName.setText("");BookAuthor.setText("");Toast.makeText(this,"UpdateSuccessed!",Toast.LENGTH_SHORT).show();}@OverridepublicvoidonItemClick(AdapterViewparent,Viewview,intposition,longid){mCursor.moveToPosition(position);BOOK_ID=mCursor.getInt(0);BookName.setText(mCursor.getString(1));BookAuthor.setText(mCursor.getString(2));}publicclassBooksListAdapterextendsBaseAdapter{privateContextmContext;privateCursormCursor;publicBooksListAdapter(Contextcontext,Cursorcursor){mContext=context;mCursor=cursor;}@OverridepublicintgetCount(){returnmCursor.getCount();}@OverridepublicObjectgetItem(intposition){returnnull;}
     @OverridepubliclonggetItemId(intposition){return0;}@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){TextViewmTextView=newTextView(mContext);mCursor.moveToPosition(position);mTextView.setText(mCursor.getString(1)+"___"+mCursor.getString(2));returnmTextView;}}}packagecom.android.tutor;importandroid.app.Activity;importandroid.content.Context;importandroid.database.Cursor;importandroid.os.Bundle;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.AdapterView;importandroid.widget.BaseAdapter;importandroid.widget.EditText;importandroid.widget.ListView;importandroid.widget.TextView;importandroid.widget.Toast;publicclassSQLiteDatabaseDemoextendsActivityimplementsAdapterView.OnItemClickListener{privateB
    ooksDBmBooksDB;privateCursormCursor;privateEditTextBookName;privateEditTextBookAuthor;privateListViewBooksList;privateintBOOK_ID=0;protectedfinalstaticintMENU_ADD=Menu.FIRST;protectedfinalstaticintMENU_DELETE=Menu.FIRST+1;protectedfinalstaticintMENU_UPDATE=Menu.FIRST+2;
     publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);setUpViews();}publicvoidsetUpViews(){mBooksDB=newBooksDB(this);mCursor=mBooksDB.select();BookName=(EditText)findViewById(R.id.bookname);BookAuthor=(EditText)findViewById(R.id.author);BooksList=(ListView)findViewById(R.id.bookslist);BooksList.setAdapter(newBooksListAdapter(this,mCursor));BooksList.setOnItemClickListener(this);}@OverridepublicbooleanonCreateOptionsMenu(Menumenu){super.onCreateOptionsMenu(menu);menu.add(Menu.NONE,MENU_ADD,0,"ADD");menu.add(Menu.NONE,MENU_DELETE,0,"DELETE");menu.add(Menu.NONE,MENU_DELETE,0,"UPDATE");returntrue;}publicbooleanonOptionsItemSelected(MenuItemitem){super.onOptionsItemSelected(item);switch(item.getItemId()){caseMENU_ADD:add();break;caseMENU_DELETE:delete();break;caseMENU_UPDATE:update();break;}returntrue;
     }publicvoidadd(){Stringbookname=BookName.getText().toString();Stringauthor=BookAuthor.getText().toString();//书名和作者都不能为空,或者退出if(bookname.equals("")||author.equals("")){return;}mBooksDB.insert(bookname,author);mCursor.requery();BooksList.invalidateViews();BookName.setText("");BookAuthor.setText("");Toast.makeText(this,"AddSuccessed!",Toast.LENGTH_SHORT).show();}publicvoiddelete(){if(BOOK_ID==0){return;}mBooksDB.delete(BOOK_ID);mCursor.requery();BooksList.invalidateViews();BookName.setText("");BookAuthor.setText("");Toast.makeText(this,"DeleteSuccessed!",Toast.LENGTH_SHORT).show();}publicvoidupdate(){Stringbookname=BookName.getText().toString();Stringauthor=BookAuthor.getText().toString();//书名和作者都不能为空,或者退出if(bookname.equals("")||author.equals("")){return;}mBooksDB.update(BOOK_ID,bookname,author);mCursor.requery();BooksList.invalidateViews();BookName.setText("");BookAuthor.setText("");Toast.makeText(this,"UpdateSuccessed!",Toast.LENGTH_SHORT).show();}
     @OverridepublicvoidonItemClick(AdapterViewparent,Viewview,intposition,longid){mCursor.moveToPosition(position);BOOK_ID=mCursor.getInt(0);BookName.setText(mCursor.getString(1));BookAuthor.setText(mCursor.getString(2));}publicclassBooksListAdapterextendsBaseAdapter{privateContextmContext;privateCursormCursor;publicBooksListAdapter(Contextcontext,Cursorcursor){mContext=context;mCursor=cursor;}@OverridepublicintgetCount(){returnmCursor.getCount();}@OverridepublicObjectgetItem(intposition){returnnull;}@OverridepubliclonggetItemId(intposition){return0;}@Overridepu
    blicViewgetView(intposition,ViewconvertView,ViewGroupparent){TextViewmTextView=newTextView(mContext);mCursor.moveToPosition(position);mTextView.setText(mCursor.getString(1)+"___"+mCursor.getString(2));returnmTextView;}}}
     第五步:运行程序效果如下:
     第六步:查看我们所建的数据库。有两种方法:第一种用命令查看:adbshelllsdata/data/com.android.tutor/databases。另一种方法是用DDMS查看,data/data下面对应的应用程序的包名下会有如在下数据库,如图所示:
     Android高手进阶教程十四)之----AndroidLocation的使用高手进阶教程(十四之十四大家好,今天说说Location,Location在Android开发中还是经常用到的,比如通过经纬度获取天气,根据Location获取所在地区详细Address(比如GoogleMap开发).等。而在Android中通过LocationManager来获取Location.通常获取Location有GPS获取,WIFI获取。我今天做一个简单的小Demo,来教大家如何获取Location,从而获取经纬度。下一节将教大家通过Location来获取Address.首先第一步:创建一个Android工程命名为LocationDemo.第二步:修改main.xml代码如下:viewplaincopytoclipboardprint?     android:layout_width="fill_parent"android:layout_height="wrap_content"android:text="longitude:"/>第三步:修改LocationDemo.java,代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importandroid.app.Activity;importandroid.content.Context;importandroid.location.Location;importandroid.location.LocationManager;importandroid.os.Bundle;importandroid.widget.TextView;publicclassLocationDemoextendsActivity{privateTextViewlongitude;privateTextViewlatitude;
     @OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);longitude=(TextView)findViewById(R.id.longitude);latitude=(TextView)findViewById(R.id.latitude);LocationmLocation=getLocation(this);
    longitude.setText("Longitude:"+mLocation.getLongitude());latitude.setText("Latitude:"+mLocation.getLatitude());}//GettheLocationbyGPSorWIFIpublicLocationgetLocation(Contextcontext){LocationManagerlocMan=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);Locationlocation=locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);if(location==null){location=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);}returnlocation;}}packagecom.android.tutor;importandroid.app.Activity;importandroid.content.Context;importandroid.location.Location;importandroid.location.LocationManager;importandroid.os.Bundle;importandroid.widget.TextView;publicclassLocationDemoextendsActivity{privateTextViewlongitude;privateTextViewlatitude;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);longitude=(TextView)findViewById(R.id.longitude);
     latitude=(TextView)findViewById(R.id.latitude);LocationmLocation=getLocation(this);longitude.setText("Longitude:"+mLocation.getLongitude());latitude.setText("Latitude:"+mLocation.getLatitude());}//GettheLocationbyGPSorWIFIpublicLocationgetLocation(Contextcontext){LocationManagerlocMan=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);Locationlocation=locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);if(location==null){location=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);}returnlocation;}}第四步:增加权限,修改AndroidManifest.xml代码如下(第16行为所增行):viewplaincopytoclipboardprint?     android:versionName="1.0">
    第五步:运行LocationDemo工程,所得效果如下(真机深圳测试):
    高手进阶教程(十五)---通过Android高手进阶教程(十五)之---通过Location获取Address的使用大家好,上一节我讲了一下如何通过LocationManager来获取Location,没有
     看过上一节的同学,可以点击如下链接返回查看:Android高手进阶教程十四之---AndroidLocation的使用!我们获取Location的目的之一肯定是有获取这个位置的详细地址,而我们有了Location在来获取Address就相对简单多了,因为GoogleApi已经封装好了方法,我们只需呀通过Location获取GeoPoint,然后在通过GeoPoint来获取我们想要的Address.下面是我做的一个简单的Demo.第一步新建一个Android工程LocationDemo,注意这里选用的是(GoogleAPIs),下面是文件目录结构:
    第二步:修改main.xml(相比第十四节增加了一个address的TextView),代码如下:viewplaincopytoclipboardprint?     android:layout_height="wrap_content"android:text="latitude:"/>第三步:修改LocationDemo.java(增加了两个方法)代码如下:viewplaincopytoclipboardprint?packagecom.android.tutor;importjava.util.List;importjava.util.Locale;importcom.google.android.maps.GeoPoint;importandroid.app.Activity;importandroid.content.Context;importandroid.location.Address;importandroid.location.Geocoder;
     importimportimportimportpublic
    android.location.Location;android.location.LocationManager;android.os.Bundle;android.widget.TextView;classLocationDemoextendsActivity{
    privateTextViewlongitude;privateTextViewlatitude;privateTextViewaddress;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.l
    ayout.main);longitude=(TextView)findViewById(R.id.longitude);latitude=(TextView)findViewById(R.id.latitude);address=(TextView)findViewById(R.id.address);LocationmLocation=getLocation(this);GeoPointgp=getGeoByLocation(mLocation);AddressmAddress=getAddressbyGeoPoint(this,gp);
    longitude.setText("Longitude:"+mLocation.getLongitude());latitude.setText("Latitude:"+mLocation.getLatitude());address.setText("Address:"+mAddress.getCountryName()+","+mAddress.getLocality());}//GettheLocationbyGPSorWIFIpublicLocationgetLocation(Contextcontext){LocationManagerlocMan=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);Locationlocation=locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);if(location==null){location=locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);}returnlocation;
     }//通过Location获取GeoPointpublicGeoPointgetGeoByLocation(Locationlocation){GeoPointgp=null;try{if(location!=null){doublegeoLatitude=location.getLatitude()*1E6;doublegeoLongitude=location.getLongitude()*1E6;gp=newGeoPoint((int)geoLatitude,(int)geoLongitude);}}catch(Exceptione){e.printStackTrace();}returngp;}//通过GeoPoint来获取AddresspublicAddressgetAddressbyGeoPoint(Contextcntext,GeoPointgp){Addressresult=null;try{if(gp!=null){Geocodergc=newGeocoder(cntext,Locale.CHINA);doublegeoLatitude=(int)gp.getLatitudeE6()/1E6;doublegeoLongitude=(int)gp.getLongitudeE6()/1E6;List
gc.getFromLocation(geoLatitude,geoLongitude,1);if(lstAddress.size()>0){result=lstAddress.get(0);}}}catch(Exceptione){e.printStackTrace();}returnresult;}}packagecom.android.tutor;importjava.util.List;lstAddress=
     importimportimportimportimportimportimportimportimportimportpublic
    java.util.Locale;com.google.android.maps.GeoPoint;android.app.Activity;android.content.Context;android.location.Address;android.location.Geocoder;android.location.Location;android.location.LocationManager;android.os.Bundle;android.widget.TextView;classLocationDemoextendsActivity{
    privateTextViewlongitude;privateTextViewlatitude;privateTextViewaddress;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);longitude=(TextView)findViewById(R.id.longitude);latitude=(TextView)findViewById(R.id.latitude);address=(TextView)findViewById(R.id.address);LocationmLocation=getLocation(this);GeoPointgp=getGeoByLocation(mLocation);AddressmAddress=getAddressbyGeoPoint(this,gp);
    longitude.setText("Longitude:"+mLocation.getLongitude());latitude.setText("Latitude:"+mLocation.getLatitude());address.setText("Address:"+mAddress.getCountryName()+","+mAddress.getLocality());}//GettheLocationbyGPSorWIFIpublicLocationgetLocation(Contextcontext){LocationManagerlocMan=(Locati
    onManager)context.getSystemService(Context.LOCATION_SERVICE);Locationlocation=locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);if(location==null){location=locMan
     .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);}returnlocation;}//通过Location获取GeoPointpublicGeoPointgetGeoByLocation(Locationlocation){GeoPointgp=null;try{if(location!=null){doublegeoLatitude=location.getLatitude()*1E6;doublegeoLongitude=location.getLongitude()*1E6;gp=newGeoPoint((int)geoLatitude,(int)geoLongitude);}}catch(Exceptione){e.printStackTrace();}returngp;}//通过GeoPoint来获取AddresspublicAddressgetAddressbyGeoPoint(Contextcntext,GeoPointgp){Addressresult=null;try{if(gp!=null){Geocodergc=newGeocoder(cntext,Locale.CHINA);doublegeoLatitude=(int)gp.getLatitudeE6()/1E6;doublegeoLongitude=(int)gp.getLongitudeE6()/1E6;List
lstAddress=
    gc.getFromLocation(geoLatitude,geoLongitude,1);if(lstAddress.size()>0){result=lstAddress.get(0);}}}catch(Exceptione){e.printStackTrace();}returnresult;}}第四步:最重要一步在AndroidManiefest.xml中导入GoogleApi(第14行代码)库,代码如下:viewplaincopytoclipboardprint?
     第五步:运行上述工程,效果如下图如示:
     高手进阶教程(十六)---AndroidAndroid高手进阶教程(十六)之---Android中万能的BaseAdapter(Spinner,ListView,GridView)的使用的使用!BaseAdapter(Spinner,ListView,GridView)的使用!大家好!今天给大家讲解一下BaseAdapter(基础适配器
    )的用法,适配器的作用主要是用来给诸如(Spinner,ListView,GridView)来填充数据的。而(Spinner,ListView,GridView)都有自己的适配器(记起来麻烦)。但是BaseAdapter(一招鲜)对他们来说却是通用的,为什么这么说呢,首先我们看
     一下API文档:
    我们看一下BaseAdapter已经实现了ListAdapter和SpinnerAdapter的接口,而GridView的适配器是实现了ListAdapter接口,只不过是二维的。所以说BaseAdapter对他们三者来说是通用的。下面我来说一下BaseAdapter的主要用法.就是我们定义一个类(如:MyAdapter)而这个类继承BaseAdapter.因为它是implements了ListAdapter和SpinnerAdapter的接口,所以要实现里面的方法,代码如下(未作任何改动的):viewplaincopytoclipboardprint?privateclassMyAdapterextendsBaseAdapter{@OverridepublicintgetCount(){//TODOAuto-generatedmethodstubreturn0;}@OverridepublicObjectgetItem(intarg0){//TODOAuto-generatedmethodstubreturnnull;}@OverridepubliclonggetItemId(intposition){//TODOAuto-generatedmethodstubreturn0;}@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){//TODOAuto-generatedmethodstubreturnnull;
     }}privateclassMyAdapterextendsBaseAdapter{@OverridepublicintgetCount(){//TODOAuto-generatedmethodstubreturn0;}@OverridepublicObjectgetItem(intarg0){//TODOAuto-generatedmethodstubreturnnull;}@OverridepubliclonggetItemId(intposition){//TODOAuto-generatedmethodstubreturn0;}@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){//TODOAuto-generatedmethodstubreturnnull;}}为了便于大家理解,老规矩写一个简单的Demo,大家按我的步骤来就OK了.第一步:新建一个Android工程命名为BaseAdapterDemo.第二步:修改main.xml代码如下:viewplaincopytoclipboardprint?     android:id="@+id/spinner"android:layout_width="fill_parent"android:layout_height="wrap_content"/>第三步:修该BaseAdapterDemo.java代码如下:
     viewplaincopytoclipboardprint?packagecom.tutor.baseadapter;importandroid.app.Activity;importandroid.graphics.Color;importandroid.os.Bundle;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.BaseAdapter;importandroid.widget.GridView;importandroid.widget.ListView;importandroid.widget.Spinner;importandroid.widget.TextView;publicclassBaseAdapterDemoextendsActivity{privateSpinnermSpinner;privateListViewmListView;privateGridViewmGridView;privateMyAdaptermMyAdapter;@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);setupViews();}publicvoidsetupViews(){mMyAdapter=newMyAdapter();mSpinner=(Spinner)findViewById(R.id.spinner);mSpinner.setAdapter(mMyAdapter);mListView=(ListView)findViewById(R.id.listview);mListView.setAdapter(mMyAdapter);mGridView=(GridView)findViewById(R.id.gridview);mGridView.setAdapter(mMyAdapter);mGridView.setNumColumns(2);}//定义自己的适配器,注意getCount和getView方法privateclassMyAdapterextendsBaseAdapter{@OverridepublicintgetCount(){//这里我就返回10了,也就是一共有10项数据项return10;}
     @OverridepublicObjectgetItem(intarg0){returnarg0;}@OverridepubliclonggetItemId(intposition){returnposition;}@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){//position就是位置从0开始,convertView是Spinner,ListView中每一项要显示的view//通常return的view也就是convertView//parent就是父窗体了,也就是Spinner,ListView,GridView了.TextViewmTextView=newTextView(getApplicationContext());mTextView.setText("BaseAdapterDemo");mTextView.setTextColor(Color.RED);returnmTextView;}}}packagecom.tutor.baseadapter;importandroid.app.Activity;importandroid.graphics.Color;importandroid.os.Bundle;importandroid.view.View;importandroid.view.ViewGroup;importandroid.widget.BaseAdapter;importandroid.widget.GridView;importandroid.widget.ListView;importandroid.widget.Spinner;importandroid.widget.TextView;publicclassBaseAdapterDemoextendsActivity{privateSpinnermSpinner;privateListViewmListView;privateGridViewmGridView;privateMyAdaptermMyAdapter;@OverridepublicvoidonCreate(BundlesavedInstanceState){
     super.onCreate(savedInstanceState);setContentView(R.layout.main);setupViews();}publicvoidsetupViews(){mMyAdapter=newMyAdapter();mSpinner=(Spinner)findViewById(R.id.spinner);mSpinner.setAdapt
    er(mMyAdapter);mListView=(ListView)findViewById(R.id.listview);mListView.setAdapter(mMyAdapter);mGridView=(GridView)findViewById(R.id.gridview);mGridView.setAdapter(mMyAdapter);mGridView.setNumColumns(2);}//定义自己的适配器,注意getCount和getView方法privateclassMyAdapterextendsBaseAdapter{@OverridepublicintgetCount(){//这里我就返回10了,也就是一共有10项数据项return10;}@OverridepublicObjectgetItem(intarg0){returnarg0;}@OverridepubliclonggetItemId(intposition){returnposition;}@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){//position就是位置从0开始,convertView是Spinner,ListView中每一项要显示的view//通常return的view也就是convertView//parent就是父窗体了,也就是Spinner,ListView,GridView了.TextViewmTextView=newTextView(getApplicationContext());mTextView.setText("BaseAdapterDemo");mTextView.setTextColor(Color.RED);returnmTextView;}
     }}第四步:运行程序效果图如下:效果图一:
     效果图二:
    等等,平时我在这里就和大家告别了,今天还没完呵呵,因为下面是我们的重点了,我们平常看的应用列表什么的,不是单单的一个TextView就可以了事的,所以我们可以在Layout里事先定义好布局。这里我新建了一个名叫baseadapter_provider.xml文件,代码如下:viewplaincopytoclipboardprint?     android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/icon"/>将getView()方法修改如下:viewplaincopytoclipboardprint?@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){//position就是位置从0开始,convertView是Spinner,ListView中每一项要显示的view//通常return的view也就是convertView//parent就是父窗体了,也就是Spinner,ListView,GridView了.//TextViewmTextView=newTextView(getApplicationContext());
     //////
    mTextView.setText("B
    aseAdapterDemo");mTextView.setTextColor(Color.RED);returnmTextView;//LayoutInflater不会的参照我的Android高手进阶教程
    (五)convertViewLayoutInflater.from(getApplicationContext()).inflate(R.layout.baseadapter_provider,null);=
    TextViewmTextView=(TextView)convertView.findViewById(R.id.textview);mTextView.setText("BaseAdapterDemo"+position);mTextView.setTextColor(Color.RED);returnconvertView;}@OverridepublicViewgetView(intposition,ViewconvertView,ViewGroupparent){//position就是位置从0开始,convertView是Spinner,ListView中每一项要显示的view//通常return的view也就是convertView//parent就是父窗体了,也就是Spinner,ListView,GridView了.//TextViewmTextView=newTextView(getApplicationContext());//mTextView.setText("BaseAdapterDemo");//mTextView.setTextColor(Color.RED);//returnmTextView;//LayoutInflater不会的参照我的Android高手进阶教程(五)convertView=LayoutInflater.from(getApplicationContext()).inflate(R.layout.baseadapter_provider,null);TextViewmTextView(TextView)convertView.findViewById(R.id.textview);mTextView.setText("BaseAdapterDemo"+position);mTextView.setTextColor(Color.RED);returnconvertView;}再次运行看一下效果图如下:=
    Android高手进阶教程十七之---Android中Intent传递对高手进阶教程(十七十七)之象的两种方法(Serializable,Parcelable)象的两种方法
     大家好,好久不见,今天要给大家讲一下Android中Intent中如何传递对象,就我目前所知道的有两种方法,一种是Bundle.putSerializable(Key,Object);另一种是Bundle.putParcelable(Key,Object);当然这些Object是有一定的条件的,前者是实现了Serializable接口,而后者是实现了Parcelable接口,为了让大家更容易理解我还是照常写了一个简单的Demo,大家就一步一步跟我来吧!第一步:新建一个Android工程命名为ObjectTranDemo(类比较多哦!)目录结构如下图:
    第二步:修改main.xml布局文件(这里我增加了两个按钮)代码如下viewplaincopytoclipboardprint?     />第三步:新建两个类一个是Person.java实现Serializable接口,另一个Book.java实现Parcelable接口,代码分别如下:Person.java:viewplaincopytoclipboardprint?packagecom.tutor.objecttran;importjava.io.Serializable;publicclassPersonimplementsSerializable{privatestaticfinallongserialVersionUID=-7060210544600464481L;privateStringname;privateintage;
     publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}}packagecom.tutor.objecttran;importjava.io.Serializable;publicclassPersonimplementsSerializable{privatestaticfinallongserialVersionUID=-7060210544600464481L;privateStringname;privateintage;publicStringgetName(){returnname;}publicvoidsetName(Stringname){this.name=name;}publicintgetAge(){returnage;}publicvoidsetAge(intage){this.age=age;}}Book.java:viewplaincopytoclipboardprint?packagecom.tutor.objecttran;importandroid.os.Parcel;importandroid.os.Parcelable;publicclassBookimplementsParcelable{privateStringbookName;privateStringauthor;privateintpublishTime;
     publicStringgetBookName(){returnbookName;}publicvoidsetBookName(StringbookName){this.bookName=bookName;}publicStringgetAuthor(){returnauthor;}publicvoidsetAuthor(Stringauthor){this.author=author;}publicintgetPublishTime(){returnpublishTime;}publicvoidsetPublishTime(intpublishTime){this.publishTime=publishTime;}publicstaticfinalParcelable.CreatorCREATOR=newCreator(){publicBookcreateFromParcel(Parcelsource){BookmBook=newBook();mBook.bookName=source.readString();mBook.author=source.readString();mBook.publishTime=source.readInt();returnmBook;}publicBook[]newArray(intsize){returnnewBook[size];}};publicintdescribeContents(){return0;}publicvoidwriteToParcel(Parcelparcel,intflags){parcel.writeString(bookName);parcel.writeString(author);parcel.writeInt(publishTime);}}packagecom.tutor.objecttran;
     importandroid.os.Parcel;importandroid.os.Parcelable;publicclassBookimplementsParcelable{privateStringbookName;privateStringauthor;privateintpublishTime;publicStringgetBookName(){returnbookName;}publicvoidsetBookName(StringbookName){this.bookName=bookName;}publicStringgetAuthor(){returnauthor;}publicvoidsetAuthor(Stringauthor){this.author=author;}publicintgetPublishTime()
    {returnpublishTime;}publicvoidsetPublishTime(intpublishTime){this.publishTime=publishTime;}publicstaticfinalParcelable.CreatorCREATOR=newCreator(){publicBookcreateFromParcel(Parcelsource){BookmBook=newBook();mBook.bookName=source.readString();mBook.author=source.readString();mBook.publishTime=source.readInt();returnmBook;}publicBook[]newArray(intsize){returnnewBook[size];}};publicintdescribeContents(){return0;}publicvoidwriteToParcel(Parcelparcel,intflags){
     parcel.writeString(bookName);parcel.writeString(author);parcel.writeInt(publishTime);}}第四步:修改ObjectTranDemo.java,并且新建两个Activity,一个是ObjectTranDemo1.java,别一个是ObjectTranDemo2.java.分别用来显示Person对像数据,和Book对象数据:,代码分别如下:ObjectTranDemo.java:viewplaincopytoclipboardprint?packagecom.tutor.objecttran;importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;publicclassObjectTranDemoextendsActivityimplementsOnClickListener{privateButtonsButton,pButton;publicfinalstaticStringSER_KEY="com.tutor.objecttran.ser";publicfinalstaticStringPAR_KEY="com.tutor.objecttran.par";publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);setupViews();}//我的一贯作风呵呵publicvoidsetupViews(){sButton=(Button)findViewById(R.id.button1);pButton=(Button)findViewById(R.id.button2);sButton.setOnClickListener(this);pButton.setOnClickListener(this);}//Serializeable传递对象的方法publicvoidSerializeMethod(){PersonmPerson=newPerson();mPerson.setName("frankie");
     mPerson.setAge(25);IntentmIntent=newIntent(this,ObjectTranDemo1.class);BundlemBundle=newBundle();mBundle.putSerializable(SER_KEY,mPerson);mIntent.putExtras(mBundle);startActivity(mIntent);}//Pacelable传递对象方法publicvoidPacelableMethod(){BookmBook=newBook();mBook.setBookName("AndroidTutor");mBook.setAuthor("Frankie");mBook.setPublishTime(2010);IntentmIntent=newIntent(this,ObjectTranDemo2.class);BundlemBundle=newBundle();mBundle.putParcelable(PAR_KEY,mBook);mIntent.putExtras(mBundle);startActivity(mIntent);}//铵钮点击事件响应publicvoidonClick(Viewv){if(v==sButton){SerializeMethod();}else{PacelableMethod();}}}packagecom.tutor.objecttran;importandroid.app.Activity;importandroid.content.Intent;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;publicclassObjectTranDemoextendsActivityimplementsOnClickListener{privateButtonsButton,pButton;publicfinalstaticStringSER_KEY="com.tutor.objecttran.ser";publicfinalstaticStringPAR_KEY="com.tutor.objecttran.par";publicvoidonCreate(Bund
    lesavedInstanceState){
     super.onCreate(savedInstanceState);setContentView(R.layout.main);setupViews();}//我的一贯作风呵呵publicvoidsetupViews(){sButton=(Button)findViewById(R.id.button1);pButton=(Button)findViewById(R.id.button2);sButton.setOnClickListener(this);pButton.setOnClickListener(this);}//Serializeable传递对象的方法publicvoidSerializeMethod(){PersonmPerson=newPerson();mPerson.setName("frankie");mPerson.setAge(25);IntentmIntent=newIntent(this,ObjectTranDemo1.class);BundlemBundle=newBundle();mBundle.putSerializable(SER_KEY,mPerson);mIntent.putExtras(mBundle);startActivity(mIntent);}//Pacelable传递对象方法publicvoidPacelableMethod(){BookmBook=newBook();mBook.setBookName("AndroidTutor");mBook.setAuthor("Frankie");mBook.setPublishTime(2010);IntentmIntent=newIntent(this,ObjectTranDemo2.class);BundlemBundle=newBundle();mBundle.putParcelable(PAR_KEY,mBook);mIntent.putExtras(mBundle);startActivity(mIntent);}//铵钮点击事件响应publicvoidonClick(Viewv){if(v==sButton){SerializeMethod();}else{PacelableMethod();
     }}}ObjectTranDemo1.java:viewplaincopytoclipboardprint?packagecom.tutor.objecttran;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclassObjectTranDemo1extendsActivity{@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);TextViewmTextView=newTextView(this);PersonmPerson=(Person)getIntent().getSerializableExtra(ObjectTranDemo.SER_KEY);mTextView.setText("Younameis:"+mPerson.getName()+"\n"+"Youageis:"+mPerson.getAge());setContentView(mTextView);}}packagecom.tutor.objecttran;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclassObjectTranDemo1extendsActivity{@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);TextViewmTextView=newTextView(this);PersonmPerson=(Person)getIntent().getSerializableExtra(ObjectTranDemo.SER_KEY);mTextView.setText("Younameis:"+mPerson.getName()+"\n"+"Youageis:"+mPerson.getAge());setContentView(mTextView);}}ObjectTranDemo2.java:viewplaincopytoclipboardprint?packagecom.tutor.objecttran;
     importimportimportpublic
    android.app.Activity;android.os.Bundle;android.widget.TextView;classObjectTranDemo2extendsActivity{
    publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);TextViewmTextView=newTextView(this);BookmBook=(Book)getIntent().getParcelableExtra(ObjectTranDemo.PAR_KEY);mTextView.setText("Booknameis:"+mBook.getBookName()+"\n"+"Authoris:"+mBook.getAuthor()+"\n"+"PublishTimeis:"+mBook.getPublishTime());setContentView(mTextView);}}packagecom.tutor.objecttran;importandroid.app.Activity;importandroid.os.Bundle;importandroid.widget.TextView;publicclassObjectTranDemo2extendsActivit
    y{publicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);TextViewmTextView=newTextView(this);BookmBook=(Book)getIntent().getParcelableExtra(ObjectTranDemo.PAR_KEY);mTextView.setText("Booknameis:"+mBook.getBookName()+"\n"+"Authoris:"+mBook.getAuthor()+"\n"+"PublishTimeis:"+mBook.getPublishTime());setContentView(mTextView);}}第五步:比较重要的一步啦,修改AndroidManifest.xml文件(将两个新增的Activity,ObjectTranDemo1,ObjectTranDemo2)申明一下代码如下(第14,15行):viewplaincopytoclipboardprint?     android:versionName="1.0">第六步:运行上述工程查看效果图啦:
     效果1:首界面:
    效果2:点击Serializable按钮
    效果3:点击Parcelable按钮:
    
    
  • 下一篇资讯: android高手文档
  • 网学推荐

    免费论文

    原创论文

    浏览:
    设为首页 | 加入收藏 | 论文首页 | 论文专题 | 设计下载 | 网学软件 | 论文模板 | 论文资源 | 程序设计 | 关于网学 | 站内搜索 | 网学留言 | 友情链接 | 资料中心
    版权所有 QQ:3710167 邮箱:3710167@qq.com 网学网 [Myeducs.cn] 您电脑的分辨率是 像素
    Copyright 2008-2015 myeducs.Cn www.myeducs.Cn All Rights Reserved
    湘ICP备09003080号