【Android源码 栏目提醒】:网学会员Android源码 为您提供ANDROID常用代码 - 操作系统参考,解决您在ANDROID常用代码 - 操作系统学习中工作中的难题,参考学习。
Android代码速查和常用基本功能实现方法0
android创建按钮ButtonbuttonnewButtonthis1
android创建输入框EditTexteditTextnewEditTextthis2
android创建文本TextViewtextViewnewTextViewthis3
android设置文本显示内容TextViewtextViewnewTextViewthistextView.setTextquothelloworldquot4
android设置文本背景色TextViewtextViewnewTextViewthistextView.setBackgroundColorColor.YELLOW5
android设置文本颜色TextViewtextViewnewTextViewthistextView.setTextColorColor.YELLOW6
android设置文本文字大小TextViewtextViewnewTextViewthistextView.setTextSize187
android设置输入框宽度EditTexteditTextnewEditTextthiseditText.setWidth2008
android设置输入框为密码框EditTexteditTextnewEditTextthiseditText.setTransformationMethodPasswordTransformationMethod.getInstance9
android设置输入框为密码框xml配置
android:passwordquottruequot10
android提示对话框的使用AlertDialog.BuilderbuildernewAlertDialog.Builderthisbuilder.setTitlequot你好quotbuilder.setPositiveButtonquotOKquotthisbuilder.show需实现
android.content.DialogInterface.OnClickListener接口11androidListView的使用ListViewlistViewnewListViewthisArrayListltHashMapltStringObjectgtgtlistnewArrayListltHashMapltStringObjectgtgtSimpleAdapteradapternewSimpleAdapterthislistR.layout.listnewStringquot标题quotnewintR.id.TextView01listView.setAdapteradapterlistView.setOnItemClickListenerthis然后实现OnItemClickListener接口publicvoidonItemClickAdapterViewltgtparentViewviewintpositionlongid12
android更新ListViewListViewlistViewnewListViewthisArrayListltHashMapltStringObjectgtgtlistnewArrayListltHashMapltStringObjectgtgtSimpleAdapteradapternewSimpleAdapterthislistR.layout.listnewStringquot标题quotnewintR.id.TextView01listView.setAdapteradapteradapter.notifyDataSetChanged//通知更新ListView13
android创建LinearLayoutLinearLayoutlayoutParantnewLinearLayoutthis14
android时间设置对话框的使用DatePickerDialogdlgnewDatePickerDialogthisthisyearmonthdaydlg.show//yearmonthday均为int型第二个参数为this时该类需要implementsOnDateSetListener并重写以下方法publicvoidonDateSetDatePickerviewintyearintmonthOfYearintdayOfMonth15
android创建FrameLayoutFrameLayoutlayoutnewFrameLayoutthis16
android触发键盘事件layout.setOnKeyListenerthis//需要implementsOnKeyListener并重写以下方法publicbooleanonKeyViewvintkeyCodeKeyEventeventreturnfalse//返回是否销毁该事件以接收新的事件比如返回true按下时可以不断执行这个方法返回false则执行一次。
17
android触发鼠标事件layout.OnTouchListenerthis//需要implementsOnTouchListener并重写以下方法publicbooleanonTouchViewvMotionEventeventreturnfalse//返回是否销毁该事件以接收新的事件比如返回true按下时可以不断执行这个方法返回false则执行一次。
18
android获得屏幕宽度和高度intwidththis.getWindow.getWindowManager.getDefaultDisplay.getWidthintheightthis.getWindow.getWindowManager.getDefaultDisplay.getHeight19
android布局添加控件LinearLayoutlayoutnewLinearLayoutthisButtonbuttonnewButtonthislayout.addViewbutton20androidintent实现activit之间跳转IntentintentnewIntentintent.setClassthisDestActivity.classstartActivityintent21androidintent设置actionIntentintentnewIntentintent.setActionintent.ACTION_DIAL22androidintent设置dataIntentintentnewIntentintent.setDataUri.parsequottel:00000000quot23androidintent传数据IntentintentnewIntentintent.putExtraquotdataquotvalue//value可以是很多种类型在接收activity中取出后强制转换或调用相应类型的get函数。
24androidintent取数据StringvalueStringgetIntent.getExtras.getquotdataquot//orStringvaluegetIntent.getExtras.getStringquotdataquot25
android利用paint和canvas画图setContentViewnewMyViewthisclassMyViewextendsViewpublicMyViewContextcontextsupercontextpublicvoidonDrawCanvascanvasPaintpaintnewPaint//创建画笔paint.setColorColor.BLUE//设置画笔颜色canvas.drawRect00100100paint//画个正方形坐标00100100。
26
android新建对话框DialogdialognewDialogthisdialog.setTitlequottestquot//设置标题dialog.addContentViewbuttonnewLayoutParams-1-1//添加控件-1是设置高度和宽度充满布局-2是按照需要设置宽度高度。
dialog.show27
android取消对话框dialog.cancel28
android对View类刷新显示view.invalidate//通过这个调用view的onDraw函数29
android使用SurfaceView画图setContentViewnewMySurfaceViewthisclassMySurfaceViewextendsSurfaceViewimplementsSurfaceHolder.CallbackSurfaceHolderholderpublicMySurfaceViewContextcontextsupercontextholdergetHolderholder.addCallbackthisclassMyThreadextendsThreadpublicvoidrunCanvascanvasholder.lockCanvasPaintpaintnewPaintpaint.setColorColor.YELLOWcanvas.drawRect100100200200paintholder.unlockCanvasAndPostcanvaspublicvoidsurfaceChangedSurfaceHolderholderintformatintwidthintheightpublicvoidsurfaceCreatedSurfaceHolderholdernewMyThread.startpublicvoidsurfaceDestroyedSurfaceHolderholder30
android获得控件findViewByIdTextViewtextViewTextViewfindViewByIdR.id.TextView0131
android十六进制设置画笔颜色PaintpaintnewPaintpaint.setColor0xffffffff//第一个ff是透明度的设置。
32
android获得String.xml中配置的字符串在activity中直接调用getTextR.string.app_name33
android去掉应用程序头部requestWindowFeatureWindow.FEATURE_NO_TITLE34
android使用SharedPreferences写入数据代码getSharedPreferencesquotdataquot0.edit.putStringquotaaquotquotbbquot.commit35
android使用SharedPreferences读取数据代码StringdatagetSharedPreferencesquotdataquot0.getStringquotitemquotquotquot//后面的quotquot是默认值没有取到则赋值为quotquot如果不想有默认可以设置null。
36
android继承SQLiteOpenHelperclassMyHelperextendsSQLiteOpenHelperpublicMyHelperContextcontextStringnameCursorFactoryfactoryintversionsupercontextnamefactoryversionpublicvoidonCreateSQLiteDatabasedbdb.execSQLquotCREATETABLEIFNOTEXISTStesttablequotquotcardnointegerprimarykeyquotquotusernamevarcharquotquotmoneyintegerquotquotquotpublicvoidonUpgradeSQLiteDatabasedbintoldVersionintnewVersiondb.execSQLquotDROPTABLEIFEXISTStesttablequotonCreatedb37
android利用SQLiteOpenHelper打开数据库MyHelperdbHelpernewMyHelperthisquottesttable.dbquotnull1SQLiteDatabasedbdbHelper.getReadableDatabase//打开只读//或者SQLiteDatabasedbdbHelper.getWritableDatabase//打开可写38
android查询数据表并显示结果Cursorcursordb.queryquottesttablequotnullnullnullnullnullnull//db的获得请参见“利用SQLiteOpenHelper打开数据库”whilecursor.isAfterLastLog.iquottestquotcursor.getString0cursor.moveToNext39androidLogcat输出打印测试信息Log.iquotTAGquotquotTESTquot40
android数据表插入数据ContentValuesvaluesnewContentValuesvalues.putquotusernamequotquotadminquotvalues.putquotmoneyquotquot10000quotdb.insertquottesttablequotnullvalues41
android使得应用全屏getWindow.setFlagsWindowManager.LayoutParams.FLAG_FULLSCREENWindowManager.LayoutParams.FLAG_FULLSCREEN42
android设置LinearLayout方向为竖layoutParant.setOrientationLinearLayout.VERTICAL43
android设置LinearLayout方向为横layoutParant.setOrientationLinearLayout.HORIZONTAL44
android数据库更新数据ContentValuesvaluesnewContentValuesvalues.putquotusernamequotquotadminquotvalues.putquotmoneyquotquot10000quotdb.updatequottesttablequotvaluesquotuserno1quotnull45
android数据库删除数据db.deletequottesttablequotquotuserno1quotnull46
android判断sd卡是否存在ifandroid.os.Environment.getExternalStorageState.equalsandroid.os.Environment.MEDIA_MOUNTEDLog.iquottestquotquotSDCARDexistsquotelseLog.iquottestquotquotSDCARDdoesntexistquot47
android创建ImageViewImageViewviewnewImageViewthisview.setImageResourceR.drawable.icon48
android提示信息ToasttoastToast.makeTextthisquothelloquotToast.LENGTH_LONGtoast.show49
android创建单选框以及单选组RadioButtonradioButtonnewRadioButtonthisRadioButtonradioButton2newRadioButtonthisradioButton.setTextquotyesquotradioButton2.setTextquotnoquotRadioGroupradioGroupnewRadioGroupthisradioGroup.addViewradioButtonradioGroup.addViewradioButton250
android新建播放器MediaPlayerMediaPlayernewMediaPlayer51
android媒体播放器使用//创建MediaPlayerMediaPlayerplayernewMediaPlayer//重置MediaPlayerplayer.resettry//设置要播放的文件的路径player.setDataSourcequot/sdcard/1.mp3quot//准备播放player.preparecatchExceptione//开始播放player.start//设置播放完毕事件player.setOnCompletionListenernewOnCompletionListenerpublicvoidonCompletionMediaPlayerplayer//播完一首循环try//再次准备播放player.preparecatchExceptioneplayer.start52
android媒体播放器暂停player.pause53
android清空cookiesCookieManager.getInstance.removeAllCookie54
android文本设置粗体TextViewtextViewnewTextViewthisTextPainttextPainttextView.getPainttextPaint.setFakeBoldTexttrue55
android网络权限配置ltuses-permissionandroid:namequotandroid.permission.INTERNETquot/gt56androidGL设定背景色gl.glClearColor0.5f0.2f0.2f1.0fgl.glClearGL10.GL_COLOR_BUFFER_BIT57
android创建GL画布publicclassMy3DViewextendsGLSurfaceViewprivateGLSurfaceView.RendererrendererpublicMy3DViewContextcontextsupercontextrenderernewMy3DRendersetRendererrenderer58
android创建复选框CheckBoxcheckBoxnewCheckBoxthis59
android复选框监听选择/取消事件checkBox.setOnCheckedChangeListenernewOnCheckedChangeListenerpublicvoidonCheckedChangedCompoundButtonbuttonViewbooleanisCheckedLog.iquotQSRquotquotTESTquot60
android创建菜单//重写下面这个函数publicbooleanonCreateOptionsMenuMenumenusuper.onCreateOptionsMenumenumenu.add011quottest1quotmenu.add022quottest2quotmenu.add033quottest3quotmenu.add044quottest4quotreturntrue61
android处理菜单选择事件publicbooleanonOptionsItemSelectedMenuItemitemintiditem.getItemIdswitchidcase1:Log.iquotQSRquotquot1quotbreakcase2:Log.iquotQSRquotquot2quotbreakcase3:Log.iquotQSRquotquot3quotbreakcase4:Log.iquotQSRquotquot4quotbreakdefault:breakreturnsuper.onOptionsItemSelecteditem62
android允许程序访问GPSXML配置ltuses-permissionandroid:namequotandroid.permission.ACCESS_FINE_LOCATIONquot/gt63
android允许程序访问GSM网络信息XML配置ltuses-permissionandroid:namequotandroid.permission.ACCESS_NETWORK_STATEquot/gt64
android允许程序访问WIFI网络信息XML配置ltuses-permissionandroid:namequotandroid.permission.ACCESS_WIFI_STATEquot/gt65
android允许程序更新电池状态XML配置ltuses-permissionandroid:namequotandroid.permission.BATTERY_STATSquot/gt66
android允许程序写短信XML配置ltuses-permissionandroid:namequotandroid.permission.WRITE_SMSquot/gt67
android允许程序设置壁纸XML配置ltuses-permissionandroid:namequotandroid.permission.SET_WALLPAPERquot/gt68
android允许程序使用蓝牙XML配置ltuses-permissionandroid:namequotandroid.permission.BLUETOOTH_ADMINquot/gt69
android允许程序打电话XML配置ltuses-permissionandroid:namequotandroid.permission.CALL_PHONEquot/gt70
android允许程序使用照相设备XML配置ltuses-permissionandroid:namequotandroid.permission.CAMERAquot/gt71
android允许程序改变网络状态XML配置ltuses-permissionandroid:namequotandroid.permission.CHANGE_NETWORK_STATEquot/gt72
android允许程序改变WIFI状态XML配置ltuses-permissionandroid:namequotandroid.permission.CHANGE_WIFI_STATEquot/gt73
android允许程序删除缓存文件XML配置ltuses-permissionandroid:namequotandroid.permission.DELETE_CACHE_FILESquot/gt74
android允许程序删除包XML配置ltuses-permissionandroid:namequotandroid.permission.DELETE_PACKAGESquot/gt75
android允许程序禁用键盘锁XML配置ltuses-permissionandroid:namequotandroid.permission.DISABLE_KEYGUARDquot/gt76
android允许程序获取任务信息XML配置ltuses-permissionandroid:namequotandroid.permission.GET_TASKSquot/gt77
android允许程序截获鼠标或键盘等事件XML配置ltuses-permissionandroid:namequotandroid.permission.INJECT_EVENTSquot/gt78
android允许程序使用socketXML配置ltuses-permissionandroid:namequotandroid.permission.INTERNETquot/gt79
android允许程序读取日历XML配置ltuses-permissionandroid:namequotandroid.permission.READ_CALENDARquot/gt80
android允许程序读取系统日志XML配置ltuses-permissionandroid:namequotandroid.permission.READ_LOGSquot/gt81
android允许程序读取所有者数据XML配置ltuses-permissionandroid:namequotandroid.permission.READ_OWNER_DATAquot/gt82
android允许程序读取短信XML配置ltuses-permissionandroid:namequotandroid.permission.READ_SMSquot/gt83
android允许程序重启设备XML配置ltuses-permissionandroid:namequotandroid.permission.REBOOTquot/gt84
android允许程序录制音频XML配置ltuses-permissionandroid:namequotandroid.permission.RECORD_AUDIOquot/gt85
android允许程序发送短信XML配置ltuses-permissionandroid:namequotandroid.permission.SEND_SMSquot/gt86
android允许程序将自己置为最前XML配置ltuses-permissionandroid:namequotandroid.permission.SET_PROCESS_FOREGROUNDquot/gt87
android创建图像图片BitmapResourcesresgetResourcesBitmapbitmapBitmapFactory.decodeResourceresR.drawable.hh88
android取得远程图片HttpURLConnectionconnHttpURLConnectionimageUrl.openConnectionconn.connectInputStreamisconn.getInputStreambitmapBitmapFactory.decodeStreamisis.close89
android允许程序发送短信XML配置ltuses-permissionandroid:namequotandroid.permission.SEND_SMSquot/gt90
android启动和结束服务startServicenewIntentquotqsr.test.MyServicequotstopServicenewIntentquotqsr.test.MyServicequot91
android创建和配置ServicepublicclassMyServiceextendsServicepublicIBinderonBindIntentarg0returnnullpublicvoidonStartIntentintentintstartIdsuper.onStartintentstartId//todosomethingwhenstartpublicvoidonDestroysuper.onDestroy//todosomethingwhenstop//xml配置ltserviceandroid:namequot.MyServicequotgtltintent-filtergtltactionandroid:namequotandroid.intent.action.TEST_SERVICEquot/gtltcategoryandroid:namequotandroid.intent.category.defaultquot/gtlt/intent-filtergtlt/servicegt92
android获得系统感应设备SensorManagersensorManagerSensorManagergetSystemServiceContext.SENSOR_SERVICE93
android设置控件布局参数//高100宽60x0y0textView01.setLayoutParamsnewAbsoluteLayout.LayoutParams100600094
android创建Drawable对象ResourcesresgetResourcesDrawabledrawableres.getDrawableR.drawable.hh95
android访问网页UriuriUri.parsequothttp://www.google.comquotIntentintentnewIntentIntent.ACTION_VIEWuristartActivityintent96
android打电话UriuriUri.parsequottel:00000000quotIntentintentnewIntentIntent.ACTION_DIALuristartActivityintent97
android播放歌曲IntentintentnewIntentIntent.ACTION_VIEWUriuriUri.parsequotfile:///sdcard/test.mp3quotintent.setDataAndTypeuriquotaudio/mp3quotstartActivityintent98
android发送邮件IntentintentnewIntentIntent.ACTION_SENDintent.putExtraIntent.EXTRA_TEXTquotTheemailtextquotintent.setTypequottext/plainquotstartActivityIntent.createChooserintentquotChooseEmailClientquot99
android发短信UriuriUri.parsequotsmsto:123456789quotIntentintentnewIntentIntent.ACTION_SENDTOuriintent.putExtraquotsms_bodyquotquotTheSMStextquotstartActivityintent100
android安装程序UriinstallUriUri.fromPartsquotpackagequotquotxxxquotnullIntentintentnewIntentIntent.ACTION_PACKAGE_ADDEDinstallUristartActivityintent101
android卸载程序UriuninstallUriUri.fromPartsquotpackagequotquotxxxquotnullIntentintentnewIntentIntent.ACTION_DELETEuninstallUristartActivityintent102
android从xml配置获得控件对象//TestActivity.javatextViewTextViewfindViewByIdR.id.TextView01//main.xmlltTextViewandroid:textquotTextView01quotandroid:idquotid/TextView01quotandroid:layout_widthquotwrap_contentquotandroid:layout_heightquotwrap_contentquotandroid:layout_xquot60pxquotandroid:layout_yquot60pxquot/gt103
android获得触摸屏压力publicbooleanonTouchViewvMotionEventeventfloatpressureevent.getPressurereturnfalse104
android给文本加上滚动条TextViewtextViewnewTextViewthistextView.setTextstringScrollViewscrollViewnewScrollViewthisscrollView.addViewtextViewsetContentViewscrollView105
android获得正在运行的所有服务publicvoidonCreateBundlesavedInstanceStatesuper.onCreatesavedInstanceStateStringBufferserviceInfonewStringBufferActivityManageractivityManagerActivityManagergetSystemServiceContext.ACTIVITY_SERVICEListltRunningServiceInfogtservicesactivityManager.getRunningServices256IteratorltRunningServiceInfogtiteratorservices.iteratorwhileiterator.hasNextRunningServiceInfosiRunningServiceInfoiterator.nextserviceInfo.appendquotpid:quot.appendsi.pidserviceInfo.appendquotprocess:quot.appendsi.processTextViewtextViewnewTextViewthistextView.setTextserviceInfo.toStringScrollViewscrollViewnewScrollViewthisscrollView.addViewtextViewsetContentViewscrollView106
android使用ContentResolver获得联系人姓名和号码ContentResolvercrgetContentResolverCursorcurcr.queryPeople.CONTENT_URInullnullnullnullcur.moveToFirstdointnameColumncur.getColumnIndexPeople.NAMEintphoneColumncur.getColumnIndexPeople.NUMBERStringnamecur.getStringnameColumnStringphoneNumbercur.getStringphoneColumnToast.makeTextthisnameToast.LENGTH_LONG.showToast.makeTextthisphoneNumberToast.LENGTH_LONG.showwhilecur.moveToNext107
android创建WebViewWebViewwebVie.
上一篇:
Android从入门到精通 经典教程
下一篇:
7*30m公路预应力混凝土连续梁桥上部结构设计