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);
    //        
    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);
    }
}
二Async ImageTask

  /*
   * //         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("/")));
四MD 5は暗号化に広く使われています。

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();
  }
}
5ストリーム中のバイトを読みだします。

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";
  }
9 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フォルダの下で定義することもできます。  xx.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"/>
  <!--    l     -->
  <stroke android:width="0.5dp" android:color="#7A7A7A"/>
  
</shape>
十一アニメファイル
//アニメフォルダ下の  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;
  }

13をダブルクリックしてアプリケーションを終了します。

 
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();
      }
  }

14 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);
        }
      }
    });
十五Calender

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);
16 DialogFragment、Dialog Fragmentの公式の推薦は使って、利益は多く言いません。

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");