一 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"/>

来源: <http://www.cnblogs.com/cyanfei/archive/2012/07/27/2612023.html>
 
</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>

2016 - 7 - 24 ..........................更新...........................

十二 ,将 Raw 加载数据库 导入 手机文件夹下

clipboard.png

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

2016 - 7 - 27 ..........................更新...........................

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

曾田生z
427 声望34 粉丝

立法者三句修改的话,全部藏书就会变成废纸。——律匠