Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Toast 自定義布局 完成圖片上傳提示

Toast 自定義布局 完成圖片上傳提示

編輯:關於Android編程

功能實現 :

\

 

Activiyt :

 

package com.lvche.lvchedingdang.activity.api_calling;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.lvche.lvcheappframelib.frame.common_utils.LogUtils;
import com.lvche.lvcheappframelib.frame.common_utils.Utils;
import com.lvche.lvchedingdang.R;
import com.lvche.lvchedingdang.activity.BaseActivity;
import com.lvche.lvchedingdang.activity.LBS.BaiduMapActivity;
import com.lvche.lvchedingdang.activity.Msc.voicedemo.IatMscActivity;
import com.lvche.lvchedingdang.activity.api_calling.adapter.APIGridAdapter;
import com.lvche.lvchedingdang.activity.common_nav.fragment.view.MyGridView;
import com.lvche.lvchedingdang.activity.contact.ContactMainActivity;
import com.lvche.lvchedingdang.activity.record_vedio.com.sli.record.videomanager.VideoManager;
import com.lvche.lvchedingdang.activity.shake.ShakeActivity;
import com.lvche.lvchedingdang.activity.signal.yi_biao_pan.TestSpeedActivity;
import com.lvche.lvchedingdang.views.custom_toast.MyToast;
import com.zxing.MipcaActivityCapture;

import java.io.File;

/**
 * 手機API調用
 */
public class APICallingActivity extends BaseActivity implements PhotoShop{
    private MyGridView gridview;
    private final static int SCANNIN_GREQUEST_CODE = 1;
    /** 使用照相機拍照獲取圖片 */
    protected static final int SELECT_PIC_BY_TACK_PHOTO = 1;
    /** 使用相冊中的圖片 */
    protected static final int SELECT_PIC_BY_PICK_PHOTO = 2;
    private Uri photoUri;
    private String  picPath;
    private boolean isCutPic;
    private String PHONE_NUM = "13800138000";
    /** 地圖定位 */
    private static final int REQUEST_CODE_MAP = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_api_calling);
        initGridView();
    }

    //初始化 gridview
    void initGridView() {
        gridview = (MyGridView)findViewById(R.id.gridview);
        gridview.setAdapter(new APIGridAdapter(this));
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                Intent intent = new Intent();
                switch ((int) id) {
                    case 0:
                        /**圖片上傳等處理**/
                        selectPhoto();
                        break;
                    case 1:
                        /** *掃描二維碼  */
                        intent.setClass(APICallingActivity.this, MipcaActivityCapture.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivityForResult(intent, SCANNIN_GREQUEST_CODE);
                        break;
                    case 2:
                        //撥打電話
                        if (PHONE_NUM != null) {
                            Intent it = new Intent();
                            it.setAction(Intent.ACTION_CALL);
                            it.setData(Uri.parse("tel:" + PHONE_NUM.trim()));
                            startActivity(it);
                        }
                        break;

                    case 3:
                        //LBS
                        //MyToast.show(getApplicationContext(),"LBS功能正在完善中。。。",Toast.LENGTH_SHORT);
                        startActivityForResult(new Intent(APICallingActivity.this, BaiduMapActivity.class), REQUEST_CODE_MAP);
                        break;
                    case 4:
                        //搖一搖
                        ///MyToast.show(getApplicationContext(),"搖一搖功能正在完善中。。。",Toast.LENGTH_SHORT);
                        startActivity(new Intent(APICallingActivity.this, ShakeActivity.class));
                        break;
                    case 5:
                        //網絡狀態監測
                        startActivity(new Intent(APICallingActivity.this, TestSpeedActivity.class));
                        //MyToast.show(getApplicationContext(),"網絡狀態監測功能正在完善中。。。",Toast.LENGTH_SHORT);
                        break;
                    case 6:
                        //語音輸入
                        //MyToast.show(getApplicationContext(),"語音輸入功能正在完善中。。。",Toast.LENGTH_SHORT);
                        startActivity(new Intent(APICallingActivity.this, IatMscActivity.class));
                        break;
                    case 7:
                        //視頻錄制
                        //MyToast.show(getApplicationContext(),"視頻錄制功能正在完善中。。。",Toast.LENGTH_SHORT);
                        startActivity(new Intent(APICallingActivity.this, VideoManager.class));
                        break;
                    case 8:
                        //通訊錄讀取
                        //MyToast.show(getApplicationContext(),"通訊錄讀取功能正在完善中。。。",Toast.LENGTH_SHORT);
                        startActivity(new Intent(APICallingActivity.this, ContactMainActivity.class));
                        break;
                }
            }
        });
    }

    /*掃描器接收結果*/
   /* @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SCANNIN_GREQUEST_CODE:
                if(resultCode == RESULT_OK){
                    Bundle bundle = data.getExtras();
                    //顯示掃描到的內容
                    //mTextView.setText(bundle.getString("result"));
                    //顯示
                    //mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
                    Toast.makeText(APICallingActivity.this,"掃描 :" + bundle.getString("result"),Toast.LENGTH_LONG).show();
                }
                break;
        }
    }*/

    /**上傳時,選擇獲取圖片的方式
     * */
    public void selectPhoto() {
        // 彈出對話框選擇
        String datas[] = { "拍照獲取照片", "從相冊中選擇照片" };
        AlertDialog.Builder dataDialogBuidler = new AlertDialog.Builder(this).setTitle("選擇圖片").setItems(datas, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                if (item == 0) { // 拍照獲取照片
                    // 開啟相機
                    takePhoto();
                }
                else {
                    // 開啟圖冊
                    pickPhoto();
                }
                dialog.dismiss();
            }
        });
        dataDialogBuidler.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int arg1) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = dataDialogBuidler.create();
        dialog.setCancelable(true);
        dialog.show();
    }

    /**
     * 拍照獲取圖片
     */
    public void takePhoto() {
        // 執行拍照前,應該先判斷SD卡是否存在
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// "android.media.action.IMAGE_CAPTURE"
            /***
             * 需要說明一下,以下操作使用照相機拍照,拍照後的圖片會存放在相冊中的 這裡使用的這種方式有一個好處就是獲取的圖片是拍照後的原圖
             * 如果不實用ContentValues存放照片路徑的話,拍照後獲取的圖片為縮略圖不清晰
             */
            ContentValues values = new ContentValues();
            photoUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);
            startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);
        } else {
            MyToast.show(getApplicationContext(), "內存卡不存在", Toast.LENGTH_SHORT);
        }
    }

    /***
     * 從相冊中取圖片
     */
    public void pickPhoto() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try{
            if (isCutPic) {

                /**切圖**/
                cropPhoto(requestCode, resultCode, data);

            } else if (requestCode == REQUEST_CODE_MAP) {
                // 地圖定位
                locationResult(data);

            }

            else {

                /**處理接收圖片結果*/
                doPhoto(requestCode, data);

            }
        } catch(Exception e) { }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**切圖**/
    private void cropPhoto(int requestCode, int resultCode, Intent data) {
        isCutPic = false;
        if (resultCode == Activity.RESULT_OK) {
            //剪切上傳
            if (requestCode == 3) {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap bitmap = extras.getParcelable("data");
                    showImage(bitmap);
                }
                //doPhoto(requestCode, data);
            } else {
                try {
                    if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
                        /** 使用相冊中的圖片 */
                        photoUri = data.getData();
                        String photoAbsolutURI = Utils.getImageAbsolutePath(this, photoUri);
                        Uri uri = Uri.fromFile(new File(photoAbsolutURI));
                        startPhotoZoom(uri);
                    } else {
                        /** 使用相機中的圖片 */
                        String[] pojo = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
                        if (cursor != null) {
                            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
                            cursor.moveToFirst();
                            picPath = cursor.getString(columnIndex);
                            //cursor.close();
                        }
                        if (picPath != null
                                && (picPath.toLowerCase().endsWith(".png") || picPath.toLowerCase().endsWith(".png")
                                || picPath.toLowerCase().endsWith(".jpg") || picPath.toLowerCase().endsWith(".jpg"))) {
                            startPhotoZoom(Uri.fromFile(new File(picPath)));
                        }
                    }
                } catch (Exception e) {
                    MyToast.show(getApplicationContext(), "溫馨提示:拾取照片失敗,請重新選擇!", Toast.LENGTH_SHORT);
                }
            }

        }
    }

    /**地圖定位*/
    private void locationResult(Intent data) {
        //緯度
        double latitude = data.getDoubleExtra("latitude", 0);
        //經度
        double longitude = data.getDoubleExtra("longitude", 0);

        String locationAddress = data.getStringExtra("address");
        if (locationAddress != null && !locationAddress.equals("")) {
            //toggleMore(more);
            //sendLocationMsg(latitude, longitude, "", locationAddress);
            MyToast.show(getApplicationContext(), "您當前的位置 :" + locationAddress + " 經緯度: " + longitude + "," + latitude + "(" + ")", Toast.LENGTH_LONG);
        } else {
            String st = getResources().getString(R.string.unable_to_get_loaction);
            MyToast.show(this, st, Toast.LENGTH_SHORT);
        }
    }

    /**
     * 裁剪圖片方法實現
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri ) {
		 /*
		 * 至於下面這個Intent的ACTION是怎麼知道的,大家可以看下自己路徑下的如下網頁
		 * yourself_sdk_path/docs/reference/android/content/Intent.html
		 * 直接在裡面Ctrl+F搜:CROP ,之前沒仔細看過,其實安卓系統早已經有自帶圖片裁剪功能, 是直接調本地庫的
		 */
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面這個crop=true是設置在開啟的Intent中設置顯示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是寬高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪圖片寬高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        //dat=file:///storage/emulated/0/DCIM/Camera/IMG_20151115_185459.jpg typ=image/jpeg
        this.startActivityForResult(intent, 3);
    }

    /**
     * 選擇圖片後,獲取圖片的路徑
     *
     * @param requestCode
     * @param data
     */
    public void doPhoto(int requestCode, Intent data) {

        try {
            if (requestCode == SELECT_PIC_BY_PICK_PHOTO) {
                if (data == null) {
                    MyToast.show(getApplicationContext(), "選擇圖片文件出錯",
                            Toast.LENGTH_SHORT);
                    return;
                }
                photoUri = data.getData();
                if (photoUri == null) {
                    MyToast.show(getApplicationContext(), "選擇圖片文件出錯",
                            Toast.LENGTH_SHORT);
                    return;
                }
                else
                {
                    /**從相冊取圖片,有些手機有異常情況,請注意* */
                    LogUtils.i("上傳回調結果onActivityResult URI:",photoUri.toString() );
                    //        		Bitmap bitmap = BitmapFactory.decodeFile(photoUri.toString());
                    try {
                        // 讀取uri所在的圖片
                        //  Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
                        String photoAbsolutURI = Utils.getImageAbsolutePath(this, photoUri);
                        final BitmapFactory.Options options  = new BitmapFactory.Options();
                        options.inJustDecodeBounds = true;
                        BitmapFactory.decodeFile(photoAbsolutURI,options);
                        options.inSampleSize = Utils.calculateInSampleSize(options, 480, 800);

                        options.inJustDecodeBounds = false;
                        Bitmap bitmap = BitmapFactory.decodeFile(photoAbsolutURI,options);

                        showImage(bitmap);

                        return;
                    }catch (Exception e){
                        LogUtils.e("[Android]", e.getMessage());
                        LogUtils.e("[Android]", "目錄為:" + photoUri);
                        return;
                    }
                }
            }

			/* 拍照獲取圖片  進行處理 * */

            String[] pojo = {MediaStore.Images.Media.DATA};
            Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
            if (cursor != null) {
                int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
                cursor.moveToFirst();
                picPath = cursor.getString(columnIndex);
                //cursor.close();
            }
            if (picPath != null
                    && (picPath.toLowerCase().endsWith(".png") || picPath.toLowerCase().endsWith(".png")
                    || picPath.toLowerCase().endsWith(".jpg") || picPath.toLowerCase().endsWith(".jpg"))) {
                try {
                    // 讀取uri所在的圖片
                    //  Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoUri);
                    String photoAbsolutURI = picPath;
                    final BitmapFactory.Options options  = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(photoAbsolutURI,options);
                    options.inSampleSize = Utils.calculateInSampleSize(options, 480, 800);

                    options.inJustDecodeBounds = false;
                    Bitmap bitmap = BitmapFactory.decodeFile(photoAbsolutURI,options);

                    showImage(bitmap);
                }catch (Exception e){
                    LogUtils.e("[Android]", e.getMessage());
                    LogUtils.e("[Android]", "目錄為:" + photoUri);
                }
            } else {
                MyToast.show(getApplicationContext(), "選擇圖片文件不正確",
                        Toast.LENGTH_SHORT);
            }

        } catch (Exception e) {
            MyToast.show(getApplicationContext(), "溫馨提示:拾取照片失敗,請重新選擇!",Toast.LENGTH_SHORT);
        }
    }

    public void showImage(Bitmap bitmap) {
        if (bitmap == null) {
            MyToast.show(getApplicationContext(),"圖片似乎不正確~!!",Toast.LENGTH_SHORT);
            return;
        }

        LayoutInflater inflater=getLayoutInflater();
        //將布局文件轉換成相應的View對象
        View layout=inflater.inflate(R.layout.toast_upload_img,(ViewGroup)findViewById(R.id.toast_layout_root));
        //從layout中按照id查找imageView對象
        ImageView imageView = (ImageView)layout.findViewById(R.id.upload_img);
        //設置ImageView的圖片
        imageView.setImageBitmap(bitmap);
        int scaleHeight = bitmap.getHeight() * 200 / bitmap.getWidth();
        imageView.setLayoutParams(new LinearLayout.LayoutParams(200,scaleHeight));
        //實例化一個Toast對象
        Toast toast=new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setView(layout);
        toast.show();
    }

    public void toGoBack(View view) {
        this.finish();
    }

}


 

toast操作部分 :

 

 public void showImage(Bitmap bitmap) {
        if (bitmap == null) {
            MyToast.show(getApplicationContext(),"圖片似乎不正確~!!",Toast.LENGTH_SHORT);
            return;
        }

        LayoutInflater inflater=getLayoutInflater();
        //將布局文件轉換成相應的View對象
        View layout=inflater.inflate(R.layout.toast_upload_img,(ViewGroup)findViewById(R.id.toast_layout_root));
        //從layout中按照id查找imageView對象
        ImageView imageView = (ImageView)layout.findViewById(R.id.upload_img);
        //設置ImageView的圖片
        imageView.setImageBitmap(bitmap);
        int scaleHeight = bitmap.getHeight() * 200 / bitmap.getWidth();
        imageView.setLayoutParams(new LinearLayout.LayoutParams(200,scaleHeight));
        //實例化一個Toast對象
        Toast toast=new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setView(layout);
        toast.show();
    }

toast 自定義布局:

 

 




    


邊框border drawable文件:

 

 




    

    

    



 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved