看源代码时,发现一个封装的选择图片方法,觉得特别好用,特地记录一下。
此框架不支持Android7.0!!!
介绍:在界面上点击“添加图片”按钮,进行选择图片(可选择多张,但张数由自己设定了的),然后点击完成,所有选择了的图片按每行三个的方式全部显示在界面上。
1.在app的gradle里的android部分添加
repositories {
maven {
url "https://jitpack.io"
}
}
在dependencies里添加
compile 'com.github.valuesfeng:androidpicturepicker:1.0.0'
compile 'com.github.bumptech.glide:glide:3.7.0'
androidpicturepicker是重点,另外glide是用于图片缓存显示用的
2.xml布局:
因为是根据选择的图片,自动显示在界面上,所以有代码生成ImageView,使用GridLayout布局,设定列数
<TextView
android:id="@+id/tvAddImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:textSize="26sp"
android:text="添加图片"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridLayout
android:id="@+id/gridLayout"
android:useDefaultMargins="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnCount="3">
GridLayout>
ScrollView>
3.activity代码:
public class HomeActivity extends AppCompatActivity {
private TextView tvAddImg;
private GridLayout gridLayout;
private final static int IMG_COUNT = 20; //可以添加的图片总数量
private String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};//存储
private final static int REQUEST_CODE_CHOOSE = 1000;
private final static int RESULT_PERMISSION = 1001;
private final static int RESULT_SUCCESS = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tvAddImg = (TextView) this.findViewById( R.id.tvAddImg);
gridLayout = (GridLayout) this.findViewById( R.id.gridLayout);
tvAddImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pickPhoto();
}
});
}
/**
* 选择图片
*/
private void pickPhoto() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int i = ContextCompat.checkSelfPermission(this, permissions[0]);
if (i != PackageManager.PERMISSION_GRANTED) {
startRequestPermission();
} else {
Picker.from(HomeActivity.this).count(IMG_COUNT).enableCamera(true).setEngine(new GlideEngine()).forResult(REQUEST_CODE_CHOOSE);
}
} else {
Picker.from(HomeActivity.this).count(IMG_COUNT).enableCamera(true).setEngine(new GlideEngine()).forResult(REQUEST_CODE_CHOOSE);
}
}
/**
* 接收图片选择结果的回调
*
* @param requestCode
* @param resultCode
* @param intent
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
int width = wm.getDefaultDisplay().getWidth();
int height = wm.getDefaultDisplay().getHeight();
List uris = PicturePickerUtils.obtainResult(intent);
if (uris != null && uris.size() != 0) {
for( int i = 0; i < uris.size(); i++){
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( (width-60)/3, height/3 );
ImageView imageView = new ImageView( HomeActivity.this);
imageView.setLayoutParams(layoutParams);
gridLayout.addView( imageView);
Glide.with( HomeActivity.this).load( uris.get( i) ).into( imageView);
}
}
}
}
// 开始提交请求权限
private void startRequestPermission() {
ActivityCompat.requestPermissions(HomeActivity.this, permissions, RESULT_SUCCESS);
}
// 用户权限 申请 的回调方法
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == RESULT_SUCCESS) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
// 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
boolean b = shouldShowRequestPermissionRationale(permissions[0]);
if (!b) {
// 用户还是想用我的 APP 的
// 提示用户去应用设置界面手动开启权限
showDialogTipUserGoToAppSettting();
}
}
}
}
}
/**
* 提示用户去应用设置界面手动开启权限
*/
private void showDialogTipUserGoToAppSettting() {
AlertDialog dialog = new AlertDialog.Builder(HomeActivity.this)
.setTitle("权限不可用")
.setMessage("请在-设置-应用管理中,允许使用存储权限")
.setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到应用设置界面
goToAppSetting();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setCancelable(false).show();
}
/**
* 跳转到当前应用的设置界面
*/
private void goToAppSetting() {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, RESULT_PERMISSION);
}
}
更新核心:使用GridView来布局。
1.xml布局:
<GridView
android:id="@+id/gridView"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:gravity="center" />
2.activity代码:
public class HomeActivity extends AppCompatActivity {
private TextView tvAddImg;
private GridView gridView;
private GridAdapter gridAdapter;
private List allUriList = new ArrayList<>();
private static int WINDOW_WIDTH;
private static int WINDOW_HEIGHT;
private final static int IMG_COUNT = 20; //一次性可以添加的图片总数量
private String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};//存储
private final static int REQUEST_CODE_CHOOSE = 1000;
private final static int RESULT_PERMISSION = 1001;
private final static int RESULT_SUCCESS = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
WindowManager wm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
WINDOW_WIDTH = wm.getDefaultDisplay().getWidth();
WINDOW_HEIGHT = wm.getDefaultDisplay().getHeight();
tvAddImg = (TextView) this.findViewById( R.id.tvAddImg);
gridView = (GridView) this.findViewById( R.id.gridView);
//为GridView设置适配器
gridAdapter = new GridAdapter();
gridView.setAdapter(gridAdapter);
tvAddImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pickPhoto();
}
});
}
/**
* 选择图片
*/
private void pickPhoto() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int i = ContextCompat.checkSelfPermission(this, permissions[0]);
if (i != PackageManager.PERMISSION_GRANTED) {
startRequestPermission();
} else {
Picker.from(HomeActivity.this).count(IMG_COUNT).enableCamera(true).setEngine(new GlideEngine()).forResult(REQUEST_CODE_CHOOSE);
}
} else {
Picker.from(HomeActivity.this).count(IMG_COUNT).enableCamera(true).setEngine(new GlideEngine()).forResult(REQUEST_CODE_CHOOSE);
}
}
/**
* 接收图片选择结果的回调
*
* @param requestCode
* @param resultCode
* @param intent
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
List uriList = PicturePickerUtils.obtainResult(intent);
allUriList.addAll( uriList);
//更新数据
gridAdapter.notifyDataSetChanged();
tvAddImg.setText("添加图片(" + allUriList.size() +"张)");
}
}
/**
* 开始提交请求权限
*/
private void startRequestPermission() {
ActivityCompat.requestPermissions(HomeActivity.this, permissions, RESULT_SUCCESS);
}
/**
* 用户权限 申请 的回调方法
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == RESULT_SUCCESS) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
// 判断用户是否 点击了不再提醒。(检测该权限是否还可以申请)
boolean b = shouldShowRequestPermissionRationale(permissions[0]);
if (!b) {
// 用户还是想用我的 APP 的
// 提示用户去应用设置界面手动开启权限
showDialogTipUserGoToAppSettting();
}
}
}
}
}
/**
* 提示用户去应用设置界面手动开启权限
*/
private void showDialogTipUserGoToAppSettting() {
AlertDialog dialog = new AlertDialog.Builder(HomeActivity.this)
.setTitle("权限不可用")
.setMessage("请在-设置-应用管理中,允许使用存储权限")
.setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到应用设置界面
goToAppSetting();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).setCancelable(false).show();
}
/**
* 跳转到当前应用的设置界面
*/
private void goToAppSetting() {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, RESULT_PERMISSION);
}
class GridAdapter extends BaseAdapter{
@Override
public int getCount() {
return allUriList.size();
}
@Override
public Object getItem(int i) {
return allUriList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView( getApplicationContext());
imageView.setLayoutParams(new GridView.LayoutParams((WINDOW_WIDTH-120)/3, (WINDOW_HEIGHT-120)/4));//设置ImageView对象布局
imageView.setAdjustViewBounds(false);//设置边界对齐
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);//设置刻度的类型
}
else {
imageView = (ImageView) convertView;
}
if( allUriList != null && allUriList.size() > 0 ){
Glide.with( HomeActivity.this).load( allUriList.get( position) ).into( imageView);//为ImageView设置图片资源
}
return imageView;
}
}
}
2.在onActivityResult(int requestCode, int resultCode,
Intent intent)函数里resultCode是对应请求是否成功啥的,根据需要自行进行区别值即对应的操作;requestCode则对应步骤1中的code,根据区分它的值,来获取自己此次选择的照片。
定义此次选择图片对应的请求码:
private final static int RESULT_IMAGE = 11;
调用函数,传入请求码:
pickPhoto(RESULT_IMAGE);
函数里使用此请求码:
private void pickPhoto(int code) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int i = ContextCompat.checkSelfPermission(this, permissions[0]);
if (i != PackageManager.PERMISSION_GRANTED) {
startRequestPermission();
} else {
Picker.from(ActEditAgencyInfo.this).count(1).enableCamera(true).setEngine(new GlideEngine()).forResult(code);
}
} else {
Picker.from(ActEditAgencyInfo.this).count(1).enableCamera(true).setEngine(new GlideEngine()).forResult(code);
}
}
在结果回调中,区分请求码:
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
List uris = PicturePickerUtils.obtainResult(intent);
if (uris != null && uris.size() != 0) {
switch (requestCode) {
case RESULT_IMAGE: Glide.with(ActEditAgencyInfo.this).load(uris.get(0)).into(ivLicense);
break;
}
}
}
}
Demo下载:[免费]选择多张本地图片网格布局-CSDN下载 http://download.csdn.net/download/an_nal/9965347