android 一些工具類匯總
一 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);
//給畫筆設(shè)置 屬性
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
/*
* //默認(rèn)開啟的線程數(shù)為128條如果超過128條會放進(jìn)隊列進(jìn)行排隊
//繼承AsyncTask時指定三個參數(shù)第一個為要傳入的參數(shù)類型 第二個為進(jìn)度的參數(shù)類型 第三個為返回結(jié)果的參數(shù)類型
//當(dāng)調(diào)用execute時首先執(zhí)行preExecute然后在執(zhí)行去啟用線程池的execute
//這時會啟動子線程去執(zhí)行doinbackground--執(zhí)行完后AsyncTask內(nèi)部會有Handler將結(jié)果返回到UI線程中
//也就是onPostExecute的這個方法然后在進(jìn)行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) {//子線程中執(zhí)行的
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 路徑 ,進(jìn)行圖片更新
Log.i("Test", result+"");
if(result!=null && imageView!= null)
imageView.setImageURI(result);//setImageURI這個方法會根據(jù)路徑加載圖片
}
}
三 截取字符串
//截取字符串 從 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();
}
}
五 讀取流中的字節(jié):
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
/**
* 讀取流中的數(shù)據(jù)
* @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();
}
}
六 解析服務(wù)器傳過來的 xml 數(shù)據(jù)流
/*
* 得到解析 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對象從網(wǎng)絡(luò)中獲取網(wǎng)頁數(shù)據(jù)
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setReadTimeout(5000);
con.setRequestMethod("GET");
if(con.getResponseCode() == 200){ //http協(xié)議,里面有相應(yīng)狀態(tài)碼的解釋,
//這里如樓上所說是判斷是否正常響應(yīng)請求數(shù)據(jù).
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;
}
七 解析 服務(wù)器傳過來的 Json 數(shù)據(jù):
/*
* 解析 Json 數(shù)據(jù)
*/
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;
}
八 向服務(wù)器提交數(shù)據(jù):
private static String sendPostRequest(String path,Map<String, String> parame, String encoding)
throws Exception {
//StringBuilder 來組合成這段數(shù)據(jù) 發(fā)給服務(wù)器 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();//默認(rèn)得到UTF-8的字節(jié)碼
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST"); //采用 POST 向服務(wù)器發(fā)送請求
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//設(shè)置Post請求的 頭字段
conn.setRequestProperty("Content-Length", String.valueOf(entity.length));//設(shè)置Post請求的 頭字段
OutputStream outStream = conn.getOutputStream();//得到數(shù)據(jù)輸出流
outStream.write(entity);//將數(shù)據(jù)寫給 http輸出流緩沖區(qū)
if(conn.getResponseCode() == 200){ //的android客戶端向服務(wù)器請求 請求碼 時 數(shù)據(jù)輸出流的緩沖區(qū)才把數(shù)據(jù)寫給服務(wù)器
//String s = conn.getResponseMessage();//這個方法得到字符串 “OK”
/*
* 得到服務(wù)器返回的數(shù)據(jù)!??! 得到服務(wù)器的返回值就可以判斷數(shù)據(jù)是否上傳成功
*/
byte[] stringData = StreamTool.read(conn.getInputStream());
String stringFlag = new String(stringData,"UTF-8");
return stringFlag; // 數(shù)據(jù)發(fā)送成功 返回 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/相應(yīng)的包名/Rsgistered_form.xml 下導(dǎo)出該文件
* @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/相應(yīng)的 Rsgistered_form.xml下取數(shù)據(jù)
* @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字段,參數(shù)為空就返回空
parmes.put("telephone_number", sp.getString("telephone_number", ""));
parmes.put("password", sp.getString("password", ""));
return parmes;
}
}
十 <!-- 設(shè)置圓角半徑 --><!-- 漸變 -->
<?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"/>
<!-- 設(shè)置圓角半徑 --><!-- 漸變 -->
<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 加載數(shù)據(jù)庫 導(dǎo)入 手機文件夾下
private SQLiteDatabase openDatabase(String dbfile) {
try {
if (!(new File(dbfile).exists())) {
//判斷數(shù)據(jù)庫文件是否存在,若不存在則執(zhí)行導(dǎo)入,否則直接打開數(shù)據(jù)庫
InputStream is = this.context.getResources().openRawResource(R.raw.china_city); //欲導(dǎo)入的數(shù)據(jù)庫
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;
}
十三 , 雙擊退出應(yīng)用
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 一些設(shè)置:
//設(shè)置點擊后 軟鍵盤的 顯示類型 ,numberDecimal帶小數(shù)點的數(shù)字
android:inputType="numberDecimal"
// 設(shè)置alertDialog中的 editView 自動彈出軟鍵盤
editView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// 設(shè)置 彈出軟鍵盤
alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
});
十五 Calendar
mCalendar= Calendar.getInstance();//獲取當(dāng)前日期
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須實現(xiàn)該接口
void showMessage(String message);
}
public static YourDialogFragment newInstance(String message){
//創(chuàng)建一個帶有參數(shù)的Fragment實例
YourDialogFragment fragment = new YourDialogFragment ();
Bundle bundle = new Bundle();
bundle.putString("message", message);
fragment.setArguments(bundle);//把參數(shù)傳遞給該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 調(diào)用):
YourDialogFragment dialog = new YourDialogFragment();
dialog.show(getFragmentManager(), "loginDialog");
- android通用xml解析方法
- 基于Android XML解析與保存的實現(xiàn)
- android layout XML解析錯誤的解決方法
- Android中使用sax解析xml文件的方法
- Android 解析XML 文件的四種方法總結(jié)
- Android中使用PULL方式解析XML文件深入介紹
- Android提高之XML解析與生成實例詳解
- Android 使用Pull方法解析XML文件的方法
- android編程之XML文件解析方法詳解(附源碼)
- Android使用Pull解析器解析xml文件的實現(xiàn)代碼
- 19個Android常用工具類匯總
- Android開發(fā)中解析xml文件XmlUtils工具類與用法示例
相關(guān)文章
Android程序打開和對輸入法的操作(打開/關(guān)閉)
整理了一下Android下對輸入法的操作:打開輸入法窗口、關(guān)閉出入法窗口、如果輸入法打開則關(guān)閉,如果沒打開則打開、獲取輸入法打開的狀態(tài)2013-05-05
關(guān)于android連續(xù)點擊出現(xiàn)多個Activity界面的解決方法
這篇文章主要介紹了關(guān)于android連續(xù)點擊出現(xiàn)多個Activity界面的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
通過WIFI(不用數(shù)據(jù)線)連接Android手機調(diào)試
本文主要介紹WIFI 鏈接手機調(diào)試,這里詳細(xì)介紹了WIFI 鏈接Android手機實現(xiàn)調(diào)試的過程,有需要的小伙伴可以參考下2016-08-08
Android App將數(shù)據(jù)寫入內(nèi)部存儲和外部存儲的示例
這篇文章主要介紹了Android App將數(shù)據(jù)寫入內(nèi)部存儲和外部存儲的示例,使用外部存儲即訪問并寫入SD卡,需要的朋友可以參考下2016-03-03

