Здравствуйте, я столкнулся со странной проблемой. Я делаю приложение для галереи, которое загружает изображения с помощью залпа и показывает их на Viewpager под названием SlideActivity, все работает правильно. Проблема: - когда я пытаюсь загрузить и поделиться 1-м изображением с видо-пейджера, ничего не происходит, но когда проведите пальцем по экрану и перейдите ко 2-му изображению, и загрузка будет работать для 2-го изображения, а когда я вернусь к 1-му изображению, теперь обмен и загрузка будут работать? Это то, что я сделал до сих пор, хочу получить совет по этому вопросу. Заранее спасибо!
SlideActivity.Java
public class TrendingSlideActivity extends AppCompatActivity {
private static final String URL = "API";
private ViewPager viewPager;
private Context context = TrendingSlideActivity.this;
private TrendingViewPagerAdapter adapter;
private int position;
private int currentImage;
private List<Trending> data;
private ImageView shareIcon, shareImage, downloadImage;
private int mAdCounter = 0;
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trending_slide_activity);
viewPager = findViewById(R.id.viewPager);
ProgressBar progressBar = findViewById(R.id.progress);
shareIcon = findViewById(R.id.shareviewpager);
downloadImage = findViewById(R.id.iv_download_slide);
//final String fileName = getIntent().getStringExtra("filename");
position = getIntent().getIntExtra("pos", 0);
progressBar.setVisibility(View.VISIBLE);
StringRequest request = new StringRequest(URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("CODE", response);
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
TrendingData users = gson.fromJson(response, TrendingData.class);
data = users.getData();
adapter = new TrendingViewPagerAdapter(context, data);
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(1);
viewPager.setCurrentItem(position);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(TrendingSlideActivity.this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int i, float v, int i1) {
}
@Override
public void onPageSelected(int i) {
currentImage = viewPager.getCurrentItem();
final String fileName1 = data.get(currentImage).getFileName();
Toast.makeText(TrendingSlideActivity.this, "===========" + fileName1, Toast.LENGTH_SHORT).show();
final String url2 = "API" + fileName1;
new LoadImage(TrendingSlideActivity.this).execute(url2);
shareIcon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onShareItem(shareImage);
}
});
downloadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveImageToGallery(shareImage);
}
});
}
@Override
public void onPageScrollStateChanged(int i) {
}
});
}
private static class LoadImage extends AsyncTask<String, Integer, Drawable> {
private WeakReference<TrendingSlideActivity> activityWeakReference;
LoadImage(TrendingSlideActivity context) {
activityWeakReference = new WeakReference<>(context);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Drawable doInBackground(String... strings) {
Bitmap bmp = null;
try {
HttpURLConnection connection = (HttpURLConnection) new URL(strings[0]).openConnection();
connection.connect();
InputStream input = connection.getInputStream();
bmp = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return new BitmapDrawable(bmp);
}
@Override
protected void onPostExecute(Drawable result) {
TrendingSlideActivity activity = activityWeakReference.get();
if (activity == null) return;
activity.shareImage = new ImageView(activity);
//Add image to ImageView
activity.shareImage.setImageDrawable(result);
}
}
public void onShareItem(View v) {
// Get access to bitmap image from view
// Get access to the URI for the bitmap
Uri bmpUri = getLocalBitmapUri((ImageView) v);
if (bmpUri != null) {
// Construct a ShareIntent with link to image
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Launch sharing dialog for image
context.startActivity(Intent.createChooser(shareIntent, "Share TrendingData"));
} else {
// ...sharing failed, handle error
}
}
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
// Use methods on Context to access package-specific directories on external storage.
// This way, you don't need to request external read/write permission.
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
// **Warning:** This will fail for API >= 24, use a FileProvider as shown below instead.
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
public boolean isStoragePermissionGranted() {
String TAG = "Storage Permission";
if (Build.VERSION.SDK_INT >= 23) {
if (this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission is granted");
return true;
} else {
Log.i(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.i(TAG, "Permission is granted");
return true;
}
}
public void saveImageToGallery(ImageView iv) {
// //to get the image from the ImageView (say iv)
// BitmapDrawable draw = (BitmapDrawable) iv.getDrawable();
// Bitmap bitmap = draw.getBitmap();
if (iv != null) {
Drawable drawable = iv.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) iv.getDrawable()).getBitmap();
} else {
}
FileOutputStream outStream = null;
String sdCard = Environment.getExternalStorageDirectory().toString();
if (isStoragePermissionGranted()) {
File dir = new File(sdCard, "/GalleryApp");
if (!dir.exists()) {
dir.mkdirs();
}
try {
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
assert bmp != null;
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(TrendingSlideActivity.this, "Saved", Toast.LENGTH_SHORT).show();
Log.i("TAAAAAAAAAAAAG", "onPictureTaken - wrote to " + outFile.getAbsolutePath());
String filePath = outFile.getPath();
MediaScannerConnection.scanFile(this,
new String[]{filePath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
Toast.makeText(TrendingSlideActivity.this,"Please Wait Image is Loading...",Toast.LENGTH_SHORT).show();
}
}
}