调用相册
int PICK_PHOTO_REQUEST = 1234;
int RESULT_CANCELED = 0;
findViewById(R.id.image_gallery).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"),PICK_PHOTO_REQUEST);
}
});
重写onActivityResult方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("TAG", "resultCode:"+resultCode);
Log.i("TAG", "requestCode:"+requestCode);
if (resultCode == RESULT_CANCELED) {
if (requestCode==PICK_PHOTO_REQUEST)
Toast.makeText(MainActivity.this, "没有选择任何图片", Toast.LENGTH_LONG).show();
}
if (requestCode == PICK_PHOTO_REQUEST) {
if (data != null) {
ContentResolver contentResolver = getContentResolver();
try {
Bitmap targetBitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(data.getData()));
Log.i("TAG", "从相册回传bitmap:" + targetBitmap);
imageView_test.setImageBitmap(targetBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
完整代码
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileNotFoundException;
public class MainActivity extends AppCompatActivity {
int PICK_PHOTO_REQUEST = 1234;
int RESULT_CANCELED = 0;
ImageView imageView_test;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_test = findViewById(R.id.imageView_test);
findViewById(R.id.image_gallery).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivityForResult(new Intent(Intent.ACTION_PICK).setType("image/*"),PICK_PHOTO_REQUEST);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("TAG", "resultCode:"+resultCode);
Log.i("TAG", "requestCode:"+requestCode);
if (resultCode == RESULT_CANCELED) {
if (requestCode==PICK_PHOTO_REQUEST)
Toast.makeText(MainActivity.this, "没有选择任何图片", Toast.LENGTH_LONG).show();
}
if (requestCode == PICK_PHOTO_REQUEST) {
if (data != null) {
ContentResolver contentResolver = getContentResolver();
try {
Bitmap targetBitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(data.getData()));
Log.i("TAG", "从相册回传bitmap:" + targetBitmap);
imageView_test.setImageBitmap(targetBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
效果演示