【发布时间】:2018-06-13 11:13:40
【问题描述】:
我有一个应用程序,有一个viewPager,我在其中添加我从图库中的照片。
在运行时很酷的旧版本中,但从 android 6.0 及更高版本开始,我需要在运行时询问权限。我已经做到了。但问题是,当我允许权限时,图像没有在viewPager 中加载,并且在第二次之后图像加载良好。
viewPager 适配器(我正在从图库中加载图片)
public class ImageAdapter extends PagerAdapter {
private ImageView imageView;
private Context context;
private LayoutInflater inflater;
public ArrayList<String> listOfAllImages = new ArrayList<>();
private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
public ImageAdapter(Context context) {
this.context = context;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestRead();
checkPermission();
} else {
getAllShownImagesPath();
}
}
private void requestRead() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
} else {
getAllShownImagesPath();
}
}
private void checkPermission(){
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
getAllShownImagesPath();
}
}
@Override
public int getCount() {
return listOfAllImages.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.photopager, null);
imageView = (ImageView) view.findViewById(R.id.photoView2);
Glide.with(context).load(listOfAllImages.get(position))
.thumbnail(1f)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imageView);
ViewPager viewPager = (ViewPager) container;
viewPager.addView(view, 0);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
private void getAllShownImagesPath() {
Uri uri;
Cursor cursor;
int column_index_data;
String absolutePathOfImage;
uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.MediaColumns.DATA,
MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
cursor = context.getContentResolver().query(uri, projection, null,
null, null);
column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
while (cursor.moveToNext()) {
absolutePathOfImage = cursor.getString(column_index_data);
listOfAllImages.add(absolutePathOfImage);
}
cursor.close();
}
}
在权限请求中点击allow后如何加载图片?
这是适配器,因为我无法覆盖 onRequestPermissionsResult。
【问题讨论】:
-
你检查过我对这个SO的回答了吗?
标签: java android permissions android-viewpager runtime-permissions