1. 程式人生 > >activity設定透明並取消跳轉動畫

activity設定透明並取消跳轉動畫

最近使用activity跳轉取消跳轉動畫,並設定為半透明,使其產生如popupwindow的效果。在這做個記錄程式碼如下:

主activity比較簡單。

package com.huayi.listview;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import 
android.widget.Toast; import com.huayi.listview.utils.BitmapHelper; /** * Created by Administrator on 2016/8/4. */ public class TestTransparentActivity extends Activity { private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_main
); imageView = (ImageView) findViewById(R.id.imageView); } public void startTransparentActivity(View view) { Intent intent = new Intent(this, TransparentActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivityForResult(intent, 100); overridePendingTransition(0
, 0);//去掉切換動畫關鍵 } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { String photoPath = data.getStringExtra("image_path"); if (TextUtils.isEmpty(photoPath)) { toastInfo("這張圖片不可用"); return; } Bitmap bitmap = BitmapHelper.getSmallBitmap(photoPath, true); imageView.setImageBitmap(bitmap); } } private void toastInfo(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } }
對應的xml檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

    <Button
android:id="@+id/onclickBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="選擇照片"
android:onClick="startTransparentActivity"/>

    <ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

透明Activity
package com.huayi.listview;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.huayi.listview.utils.BitmapHelper;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2016/8/4.
 */
public class TransparentActivity extends Activity  implements View.OnClickListener {
    private Button takePhoto_Button, selectPhoto_Button, cancel_Button;
    private int startMode = 1;
    private String mPhotoPath; //, photoName;
    // private Handler handler;
private TextView textMessage = null;
    // private Timer timer = null;
    // private TimerTask task = null;
    // private int count = 2; //dialog display 2s
private View cancelBtn;
    private int phtoW, phtoH;
    private static final int DEFAULT_SIZE = 100;
    public static final String IMAGE_W = "photo_w";
    public static final String IMAGE_H = "photo_h";
    @Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_take_photo);

        if (null != savedInstanceState) {
            startMode = savedInstanceState.getInt("upload_mode", 1);
            phtoW = savedInstanceState.getInt(IMAGE_W, DEFAULT_SIZE);
            phtoH = savedInstanceState.getInt(IMAGE_H, DEFAULT_SIZE);
            mPhotoPath = savedInstanceState.getString("photoPath");
            setResultOk();
            return;
        } else {
            Intent intent = getIntent();
            if (null == intent) {
                startMode = 1;
                phtoW = DEFAULT_SIZE;
                phtoH = DEFAULT_SIZE;
            } else {
                startMode = intent.getIntExtra("upload_mode", 1);
                phtoW = intent.getIntExtra(IMAGE_W, DEFAULT_SIZE);
                phtoH = intent.getIntExtra(IMAGE_H, DEFAULT_SIZE);
            }
        }

        takePhoto_Button = (Button) findViewById(R.id.take_photo);
        takePhoto_Button.setOnClickListener(this);

        cancelBtn = findViewById(R.id.finish);
        cancelBtn.setOnClickListener(this);

        cancel_Button = (Button) findViewById(R.id.cancel_button);
        cancel_Button.setOnClickListener(this);

        selectPhoto_Button = (Button) findViewById(R.id.select_photo);
        selectPhoto_Button.setOnClickListener(this);

}

    @Override
public void onClick(View v) {
        switch (v.getId()) {
            case R.id.take_photo: //進入拍照
{
                enterTakePhoto();
            }
            break;

            case R.id.select_photo: //進入選擇照片
{
                //進入選擇圖片
Intent intent = new Intent();
                intent.setType("image/*");
                //intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setAction(Intent.ACTION_PICK);
                //Intent.ACTION_PICK
startActivityForResult(intent, 200);
            }
            break;

            case R.id.cancel_button: {
                this.finish();
                overridePendingTransition(0,0);
            }
            break;
            case R.id.finish:
                finish();
                overridePendingTransition(0,0);
                break;
            default:
                break;
        }

    }

    @Override
protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("upload_mode", startMode);
        outState.putInt(IMAGE_W, phtoW);
        outState.putInt(IMAGE_H, phtoH);
        outState.putString("photoPath", mPhotoPath);
    }

    @Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        startMode = savedInstanceState.getInt("upload_mode", 1);
        phtoW = savedInstanceState.getInt(IMAGE_W, DEFAULT_SIZE);
        phtoH = savedInstanceState.getInt(IMAGE_H, DEFAULT_SIZE);
        mPhotoPath = savedInstanceState.getString("photoPath");
    }

    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return "/" + dateFormat.format(date) + ".jpg";
    }

    private void enterTakePhoto() {
        String SDState = Environment.getExternalStorageState();
        //相機進入
if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            //  Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
try {
                mPhotoPath = Environment.getExternalStorageDirectory()
                        + "/e-car";
                File dir = new File(mPhotoPath);
                if (!dir.exists()) {
                    if (!dir.mkdirs())
                        dir.mkdir();
                }

                mPhotoPath += "/Photo";
                File dir1 = new File(mPhotoPath);
                if (!dir1.exists()) {
                    if (!dir1.mkdirs())
                        dir1.mkdir();
                }

                mPhotoPath += getPhotoFileName();
                File file = new File(mPhotoPath);
                // file.delete();
if (!file.exists()) {
                    file.createNewFile();
                }
                Intent intent = new Intent(
                        MediaStore.ACTION_IMAGE_CAPTURE);
                Uri u = Uri.fromFile(file);
                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                startActivityForResult(intent, 100);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "請插入sdcard!", Toast.LENGTH_LONG).show();
        }

//        ContentValues values = new ContentValues();
//        // values.put(MediaStore.Images.Media.TITLE, photoName);
//        values.put(MediaStore.Images.Media.TITLE, getPhotoFileName());
//        Uri mCapturedImageURI = getContentResolver().insert(
//                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//        Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
//        startActivityForResult(intentPicture, 100);
}

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("uploadPhoto_Activity", "requestCode= " + requestCode + ";resultCode=" + resultCode);

        //取消
if (resultCode == RESULT_CANCELED) {
            return;
        }

        //拍照返回
if (requestCode == 100) //
{
            Log.i("onActivityResult", "imagePath = " + mPhotoPath);

            if (2 == startMode) {
                startPhotoZoom(Uri.fromFile(new File(mPhotoPath)));
                // startPhotoCrop(Uri.fromFile(new File(mPhotoPath)));
return;
            } else {
                setResultOk();
                //startUpload();
}
        }
        //選擇照片返回
else if (requestCode == 200) {
            if (data == null) {
                // Toast.makeText(this, "選擇圖片檔案出錯", Toast.LENGTH_LONG).show();
return;
            }
            Uri photoUri;
            photoUri = data.getData();
            if (photoUri == null) {
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    try {
                        mPhotoPath = BitmapHelper.WriteBitmapToSdCard(photo);
                        setResultOk();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
e.printStackTrace();
                        //Toast.makeText(this, "選擇圖片檔案出錯", Toast.LENGTH_LONG).show();
return;
                    }
                } else {
                    // Toast.makeText(this, "選擇圖片檔案出錯", Toast.LENGTH_LONG).show();
}
                return;
            }

            if (2 == startMode) {
                startPhotoZoom(photoUri);
                // startPhotoCrop(photoUri);
return;
            } 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();
                    mPhotoPath = cursor.getString(columnIndex);
                    cursor.close();
                }
                Log.i("onActivityResult", "imagePath = " + mPhotoPath);
                if (mPhotoPath == null) {
                    Log.e("upload", "mPhotoPath is null");
                    // Toast.makeText(this, "選擇圖片檔案出錯", Toast.LENGTH_LONG).show();
return;
                }

                setResultOk();
            }
        }
        //擷取照片返回
else if (requestCode == 300) {
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");
                try {
                    mPhotoPath = BitmapHelper.WriteBitmapToSdCard(photo);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
e.printStackTrace();
                    return;
                }

                //  startUpload();
setResultOk();
                //  photo.recycle();
}
        }

    }

    private void setResultOk() {
        Intent intent = new Intent();
        if (TextUtils.isEmpty(mPhotoPath)) {
            Toast.makeText(this, "圖片檔案出錯!", Toast.LENGTH_LONG).show();
            setResult(Activity.RESULT_CANCELED, intent);
        } else {
            intent.putExtra("image_path", mPhotoPath);
            setResult(Activity.RESULT_OK, intent);
        }
        finish();
    }

    /**
     * 裁剪圖片方法實現
     *
     * @param uri
*/
public void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 設定裁剪
intent.putExtra("crop", "true");
        // aspectX aspectY 是寬高的比例
intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪圖片寬高
intent.putExtra("outputX", phtoW);
        intent.putExtra("outputY", phtoH);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 300);
    }

    /**
     * 裁剪圖片方法實現
     *
     * @param uri
*/
public void startPhotoCrop(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 設定裁剪
intent.putExtra("crop", "true");
        // aspectX aspectY 是寬高的比例
float y, x;
        if (phtoW >= phtoH) {
            y = 1;
            x = phtoW / phtoH;
        } else {
            x = 1;
            y = phtoH / phtoW;
        }
        intent.putExtra("aspectX", x);
        intent.putExtra("aspectY", y);
        // outputX outputY 是裁剪圖片寬高
intent.putExtra("outputX", phtoW);
        intent.putExtra("outputY", phtoH);
        intent.putExtra("scale", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra("return-data", false);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        startActivityForResult(intent, 300);
    }




   
@Override
protected void onDestroy() {
//        if (timer != null) {
//            timer.cancel();
//        }
super.onDestroy();
    }
}
對應的xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

    <View
android:id="@+id/finish"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000" />

    <RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginLeft="5.0dip"
android:layout_marginRight="5.0dip"
android:background="@drawable/trans"
android:gravity="center_vertical">

        <Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30.0dip"
android:layout_marginRight="30.0dip"
android:layout_marginTop="10.0dip"
android:background="@drawable/btn_white_to_red_selector"
android:clickable="true"
android:gravity="center"
android:text="拍照"
android:textColor="@color/red_to_white_color_selector"
/>

        <Button
android:id="@+id/select_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/take_photo"
android:layout_marginLeft="30.0dip"
android:layout_marginRight="30.0dip"
android:layout_marginTop="20.0dip"
android:background="@drawable/btn_white_to_red_selector"
android:clickable="true"
android:gravity="center"
android:text="選擇照片"
android:textColor="@color/red_to_white_color_selector"
/>

        <Button
android:id="@+id/cancel_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/select_photo"
android:layout_marginLeft="30.0dip"
android:layout_marginRight="30.0dip"
android:layout_marginTop="20.0dip"
android:background="@drawable/btn_white_to_red_selector"
android:clickable="true"
android:gravity="center"
android:text="取消"
android:layout_marginBottom="10dp"
android:textColor="@color/red_to_white_color_selector"
/>
    </RelativeLayout>

</FrameLayout>

在style裡宣告透明Activity主題
<style name="Transparent" parent="Theme.AppCompat.Light">
    <item name="android:windowBackground">@color/transparent_background</item>
    <!-- <item name="android:windowNoTitle">true</item> -->
<item name="android:windowIsTranslucent">true</item>
    <!--<item name="android:windowAnimationStyle">@android:style/Animation.Translucent</item>-->//切換動畫
</style>
在配置檔案裡應用
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.huayi.listview">

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme">
        <activity android:name=".TestTransparentActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.huayi.listview.TransparentActivity" android:theme="@style/Transparent"/>
    </application>

</manifest>