package com.bwie.zhangyuke20170913;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private ImageView ivIcon;
private Button bt_qc;
private Button bt_add;
private Button bt_hc;
private String path;
private File file;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_hc = (Button) findViewById(R.id.bt_hc);
bt_add = (Button) findViewById(R.id.bt_add);
bt_qc = (Button) findViewById(R.id.bt_qc);
ivIcon = (ImageView) findViewById(R.id.ivIcon);
try {
//路径
path = Environment.getExternalStorageDirectory() + "/tu.png";
file = new File(path);
} catch (Exception e) {
e.printStackTrace();
}
//向sdCard缓存
bt_hc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
if (!file.exists()){
try {
file.createNewFile();
FileOutputStream fos=new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,50,fos);
Toast.makeText(MainActivity.this, "缓存成功", Toast.LENGTH_SHORT).show();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
//从SdCard取出图片
bt_add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (file.exists()){
Bitmap bitmap = BitmapFactory.decodeFile(path);
ivIcon.setImageBitmap(bitmap);
}
}
});
//删除图片
bt_qc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
file.delete();
Bitmap bitmap = BitmapFactory.decodeFile(path);
ivIcon.setImageBitmap(bitmap);
}
});
}
}