直接上代码
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"
>
<ImageView
android:id="@+id/imageView1"
android:adjustViewBounds="true"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:text="切换图片"
android:onClick="onClickChange"
/>
</LinearLayout>
java文件
package wnl.myndk;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.util.Calendar;
public class Demo2 extends Activity {
private ImageView imageView;
private File tempFile;
private SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo2);
imageView = (ImageView) findViewById(R.id.imageView1); //初始化ImageView控件
sp = getSharedPreferences("HeaderImage", MODE_PRIVATE);
String path = sp.getString("tempFile", "");
if (!"".equals(path)) {
imageView.setImageDrawable(Drawable.createFromPath(path));
}
}
public void onClickChange(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.putExtra("crop", "true");// 出现剪辑的小方框,不然没有剪辑功能,只能选取图片
//宽高比
intent.putExtra("aspectX", 1); // 出现放大和缩小
intent.putExtra("aspectY", 1); // 出现放大和缩小
intent.setType("image/*"); // 查看类型 详细的类型在 com.google.android.mms.ContentType
String path = sp.getString("tempFile", "");
if (!"".equals(path))
tempFile = new File(path);
else {
tempFile = new File("/sdcard/headerImage" + ".jpg");
sp.edit().putString("tempFile", tempFile.getAbsolutePath()).commit();
}
File temp = new File("/sdcard/headerImage/");//自已项目 文件夹
if (!temp.exists()) {
temp.mkdir();
}
intent.putExtra("output", Uri.fromFile(tempFile)); // 传入目标文件
intent.putExtra("outputFormat", "JPEG"); //输入文件格式
Intent wrapperIntent = Intent.createChooser(intent, "选择头像图片"); //开始 并设置标题
startActivityForResult(wrapperIntent, 1); // 设返回 码为 1 onActivityResult 中的 requestCode 对应
}
//调用成功反回方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1:
imageView.setImageDrawable(Drawable.createFromPath(tempFile.getAbsolutePath()));
Toast.makeText(Demo2.this, tempFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
break;
}
}
}