android 一些工具类汇总
程序员文章站
2024-03-07 13:08:45
一 paint ,canvas
public class drawview extends view{
private paint paint1;
p...
一 paint ,canvas
public class drawview extends view{ private paint paint1; public drawview(context context,attributeset set ){ super(context,set); } public void ondraw(canvas canvas){ super.ondraw(canvas); //new 一个画笔对象 paint1= new paint(); canvas.drawcolor(color.transparent); //给画笔设置 属性 paint1.setantialias(true); paint1.setcolor(color.gray); paint1.setstyle(paint.style.fill); paint1.setstrokewidth(3); //画一个圆 //canvas.drawcircle(arg0, arg1, arg2, arg3); canvas.drawcircle(10, 10, 5, paint1); } }
二 asyncimagetask
/* * //默认开启的线程数为128条如果超过128条会放进队列进行排队 //继承asynctask时指定三个参数第一个为要传入的参数类型 第二个为进度的参数类型 第三个为返回结果的参数类型 //当调用execute时首先执行preexecute然后在执行去启用线程池的execute //这时会启动子线程去执行doinbackground--执行完后asynctask内部会有handler将结果返回到ui线程中 //也就是onpostexecute的这个方法然后在进行ui界面的更新 */ private void asyncimageload(imageview imageview, string path) { asyncimagetask asyncimagetask = new asyncimagetask(imageview); asyncimagetask.execute(path); } private final class asyncimagetask extends asynctask<string, integer, uri>{ private imageview imageview; public asyncimagetask(imageview imageview) { this.imageview = imageview; } protected uri doinbackground(string... params) {//子线程中执行的 try { uri uu = contactservice.getimage(params[0], cache);//将uri路径抛给主线程 system.out.println(uu+" zuuuuuuuu"); return uu; } catch (exception e) { e.printstacktrace(); } return null; } protected void onpostexecute(uri result) {//运行在主线程,获取 uri 路径 ,进行图片更新 log.i("test", result+""); if(result!=null && imageview!= null) imageview.setimageuri(result);//setimageuri这个方法会根据路径加载图片 } }
三 截取字符串
//截取字符串 从 0 到 第一个 "/" 字符 string name = result.substring(0,result.indexof("/")); //截取字符串 从 第一个 字符 “/” 到 最后一个 “/” 字符 string name = result.substring(result.indexof("/")+1, result.lastindexof("/")));
四 md5广泛用于加密
import java.security.messagedigest; import java.security.nosuchalgorithmexception; public class md5 { public static string getmd5(string content) { try { messagedigest digest = messagedigest.getinstance("md5"); digest.update(content.getbytes()); return gethashstring(digest); } catch (nosuchalgorithmexception e) { e.printstacktrace(); } return null; } private static string gethashstring(messagedigest digest) { stringbuilder builder = new stringbuilder(); for (byte b : digest.digest()) { builder.append(integer.tohexstring((b >> 4) & 0xf)); builder.append(integer.tohexstring(b & 0xf)); } return builder.tostring(); } }
五 读取流中的字节:
import java.io.bytearrayoutputstream; import java.io.inputstream; public class streamtool { /** * 读取流中的数据 * @param instream * @return * @throws exception */ public static byte[] read(inputstream instream) throws exception{ bytearrayoutputstream outstream = new bytearrayoutputstream(); byte[] buffer = new byte[1024]; int len = 0; while( (len = instream.read(buffer)) != -1){ outstream.write(buffer, 0, len); } instream.close(); return outstream.tobytearray(); } }
六 解析服务器传过来的 xml 数据流
/* * 得到解析 xml 后 的 contact list 集合 */ public static list<contact> getcontacts() throws exception { string path = stringtools.geturl_list_xml; url url = new url(path); //urlconnection与httpurlconnection都是抽象类,无法直接实例化对象。 //其对象主要通过url的openconnection方法获得。 //利用httpurlconnection对象从网络中获取网页数据 httpurlconnection con = (httpurlconnection) url.openconnection(); con.setreadtimeout(5000); con.setrequestmethod("get"); if(con.getresponsecode() == 200){ //http协议,里面有相应状态码的解释, //这里如楼上所说是判断是否正常响应请求数据. return parsexml(con.getinputstream()); //fff //return streamtool.read(con.getinputstream()); } return null; }
其中 parsexml(con.getinputstream());
/* * 解析xml */ private static list<contact> parsexml(inputstream xml) throws exception { list<contact> contacts = new arraylist<contact>(); contact contact = null; xmlpullparser pullparser = xml.newpullparser(); pullparser.setinput(xml,"utf-8"); int event = pullparser.geteventtype(); while(event != xmlpullparser.end_document){ switch (event) { case xmlpullparser.start_tag : if("contact".equals(pullparser.getname())){ contact = new contact(); contact.id = new integer(pullparser.getattributevalue(0)); }else if("name".equals(pullparser.getname())){ contact.name = pullparser.nexttext();// .nexttext 不是 .gettext !!!! }else if("image".equals(pullparser.getname())){ contact.imageurl = pullparser.getattributevalue(0);//fff } break; case xmlpullparser.end_tag : if("contact".equals(pullparser.getname())){ contacts.add(contact); contact = null; } break; } event = pullparser.next(); } return contacts; }
七 解析 服务器传过来的 json 数据:
/* * 解析 json 数据 */ private static list<secondactivity_goods_bean> parsejson(inputstream inputstream) throws exception { list<secondactivity_goods_bean> secondactivity_goods_beans = new arraylist<secondactivity_goods_bean>(); secondactivity_goods_bean goodbean = null; byte[] data = streamtool.read(inputstream); string json = new string(data); jsonarray array = new jsonarray(json); for(int i=0;i<array.length();i++){ jsonobject jsonobject = array.getjsonobject(i); jsonobject.getstring("imageurl"); jsonobject.getstring("imagecontent"); jsonobject.getstring("goodsprice"); goodbean = new secondactivity_goods_bean(jsonobject.getstring("imageurl"), jsonobject.getstring("imagecontent"), jsonobject.getstring("goodsprice")); secondactivity_goods_beans.add(goodbean); } return null; }
八 向服务器提交数据:
private static string sendpostrequest(string path,map<string, string> parame, string encoding) throws exception { //stringbuilder 来组合成这段数据 发给服务器 telephone_number=telephone_number&password=password stringbuilder data = new stringbuilder(); if(parame != null && !parame.isempty()){ for(map.entry<string, string> entry:parame.entryset()){ data.append(entry.getkey()).append("="); data.append(urlencoder.encode(entry.getvalue(), encoding)); data.append("&"); } data.deletecharat(data.length() -1);//最后会多出 “&” } byte[] entity = data.tostring().getbytes();//默认得到utf-8的字节码 httpurlconnection conn = (httpurlconnection) new url(path).openconnection(); conn.setconnecttimeout(5000); conn.setrequestmethod("post"); //采用 post 向服务器发送请求 conn.setrequestproperty("content-type", "application/x-www-form-urlencoded");//设置post请求的 头字段 conn.setrequestproperty("content-length", string.valueof(entity.length));//设置post请求的 头字段 outputstream outstream = conn.getoutputstream();//得到数据输出流 outstream.write(entity);//将数据写给 http输出流缓冲区 if(conn.getresponsecode() == 200){ //的android客户端向服务器请求 请求码 时 数据输出流的缓冲区才把数据写给服务器 //string s = conn.getresponsemessage();//这个方法得到字符串 “ok” /* * 得到服务器返回的数据!!! 得到服务器的返回值就可以判断数据是否上传成功 */ byte[] stringdata = streamtool.read(conn.getinputstream()); string stringflag = new string(stringdata,"utf-8"); return stringflag; // 数据发送成功 返回 true } return "submit_fail"; }
九 sharedpreferences
public class sharedpreferences_service { private context context; private sharedpreferences sp; public sharedpreferences_service(context applicationcon){ this.context = applicationcon; } /** * 将 文件存储在 file explorer的data/data/相应的包名/rsgistered_form.xml 下导出该文件 * @param name * @param telephone_number * @param password */ public void setparament(string name,string telephone_number,string password){ sp = context.getsharedpreferences("rsgistered_form", context.mode_append); editor et = sp.edit(); et.putstring("name", name); et.putstring("telephone_number",telephone_number); et.putstring("password",password); et.commit(); } /** * 在文件夹 file explorer的data/data/相应的 rsgistered_form.xml下取数据 * @return */ public map<string, string> getparament(){ map<string, string> parmes = new hashmap<string, string>(); sp = context.getsharedpreferences("rsgistered_form", context.mode_append); parmes.put("name", sp.getstring("name", ""));//获得name字段,参数为空就返回空 parmes.put("telephone_number", sp.getstring("telephone_number", "")); parmes.put("password", sp.getstring("password", "")); return parmes; } }
十 <!-- 设置圆角半径 --><!-- 渐变 -->
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <!-- 圆角 --> <corners android:radius="9dp" android:topleftradius="2dp" android:toprightradius="2dp" android:bottomleftradius="2dp" android:bottomrightradius="2dp"/> <!-- 设置圆角半径 --><!-- 渐变 --> <gradient android:startcolor="@android:color/white" android:centercolor="@android:color/black" android:endcolor="@android:color/black" android:uselevel="true" android:angle="45" android:type="radial" android:centerx="0" android:centery="0" android:gradientradius="90"/> <!-- 间隔 --> <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp"/> <!-- 各方向的间隔 --><!-- 大小 --> <size android:width="50dp" android:height="50dp"/> <!-- 宽度和高度 --><!-- 填充 --> <solid android:color="@android:color/white"/> <!-- 填充的颜色 --><!-- 描边 --> <stroke android:width="2dp" android:color="@android:color/black" android:dashwidth="1dp" android:dashgap="2dp"/> </shape>
也可以在 drawable 文件夹下 在定义个 xxx.xml 使用 selector
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/button_pressed_bg" android:state_pressed="true"></item> <item android:drawable="@drawable/shape_image"></item> </selector>
定义一个有四个角弧度的 长方形背景
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <!-- 指定4個角的弧度 --> <corners android:topleftradius="2px" android:toprightradius="2px" android:bottomleftradius="2px" android:bottomrightradius="2px"/> <!-- 指定背景顏色 --> <solid android:color="#ffffff"/> <!-- 指定框條的顏色的寬度 --> <stroke android:width="0.5dp" android:color="#7a7a7a"/> </shape>
十一 anim文件
// anim 文件夹下 的 out.xml 动画文件
<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:shareinterpolator="false"> <!-- 100%p 的 p 是指从父类view 的 指定位置 0 到 起始位 100%--> <!-- 位移 --> <translate android:fromxdelta="0%p" android:toxdelta="100%p" android:duration="1000" /> <!-- 透明度 --> <alpha android:fromalpha="1.0" android:toalpha="0.5" android:duration="500" /> </set>
十二 ,将 raw 加载数据库 导入 手机文件夹下
private sqlitedatabase opendatabase(string dbfile) { try { if (!(new file(dbfile).exists())) { //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库 inputstream is = this.context.getresources().openrawresource(r.raw.china_city); //欲导入的数据库 fileoutputstream fos = new fileoutputstream(dbfile); byte[] buffer = new byte[buffer_size]; int count = 0; while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close(); is.close(); } return sqlitedatabase.openorcreatedatabase(dbfile, null); } catch (filenotfoundexception e) { plog.e("file not found"); e.printstacktrace(); } catch (ioexception e) { plog.e("io exception"); e.printstacktrace(); } return null; }
十三 , 双击退出应用
public class doubleclickexit { /** * 双击退出检测, 阈值 2000ms */ public static long lastclick = 0l; private static final int threshold = 2000;// 2000ms public static boolean check() { long now = system.currenttimemillis(); boolean b = now - lastclick < threshold; lastclick = now; return b; } } @override public void onbackpressed() { if (!doubleclickexit.check()) { toastutil.showshort(getstring(r.string.double_exit)); } else { finish(); } }
十四 edittext 一些设置:
//设置点击后 软键盘的 显示类型 ,numberdecimal带小数点的数字 android:inputtype="numberdecimal" // 设置alertdialog中的 editview 自动弹出软键盘 editview.setonfocuschangelistener(new view.onfocuschangelistener() { @override public void onfocuschange(view v, boolean hasfocus) { if (hasfocus) { // 设置 弹出软键盘 alertdialog.getwindow().setsoftinputmode(windowmanager.layoutparams.soft_input_state_always_visible); } } });
十五 calendar
mcalendar= calendar.getinstance();//获取当前日期 int_year = mcalendar.get(calendar.year); int_month = mcalendar.get(calendar.month); int_dat = mcalendar.get(calendar.day_of_month); int_lastday=mcalendar.getactualmaximum(calendar.day_of_month); int_week = mcalendar.get(calendar.day_of_week);
十六 dialogfragment ,dialogfragment官方推荐使用的,好处就不多说
public class yourdialogfragment extends dialogfragment { public interface dialogfragmentdataimp{//定义一个与activity通信的接口,使用该dialogfragment的activity须实现该接口 void showmessage(string message); } public static yourdialogfragment newinstance(string message){ //创建一个带有参数的fragment实例 yourdialogfragment fragment = new yourdialogfragment (); bundle bundle = new bundle(); bundle.putstring("message", message); fragment.setarguments(bundle);//把参数传递给该dialogfragment return fragment; } @override public dialog oncreatedialog(bundle savedinstancestate) { view customview = layoutinflater.from(getactivity()).inflate( r.layout.fragment_edit_bill_dialog, null); //butterknife.bind(this,customview); mcontext = getactivity(); initview(); return new alertdialog.builder(getactivity()).setview(customview) .create(); }
使用(在 activity 或 fragment 调用):
yourdialogfragment dialog = new yourdialogfragment(); dialog.show(getfragmentmanager(), "logindialog");