简体   繁体   中英

Oreo ViewPager to display images from external storage filepaths

So I am very new to both Java and Android and am working on an app for a project. Within the app I would like to have my own image gallery / viewer specifically for the images we will be saving with the app. As such I want to use a ViewPager to slide through the images, and have created a custom pager adapter. Here are the relevant files:

CustomSwipeAdapter.java

package app.rpass;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.io.File;
import java.util.ArrayList;

public class CustomSwipeAdapter extends PagerAdapter {

    ArrayList<String> f = new ArrayList<String>();// list of file paths
    File[] listFile;
    private Context ctx;
    private LayoutInflater layoutInflater;
    ArrayList<Bitmap> images = new ArrayList<Bitmap>(); //list of bitmaps

    public CustomSwipeAdapter(Context ctx){
        this.ctx = ctx;
    }

    @Override
    public int getCount() {
        return images.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return (view == (LinearLayout)object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View item_view = layoutInflater.inflate(R.layout.swipe_layout,container,false);
        TextView textView = (TextView) item_view.findViewById(R.id.image_count);
        String[] output = f.get(position).split("/");
        textView.setText(output[output.length-1]);
        ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView2);
        imageView.setImageBitmap(images.get(position));
        container.addView(item_view);
        return item_view;

    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((LinearLayout)object);
    }

    public void getFromSdcard()
    {
        File file= new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"pictures");
        if (file.isDirectory()) {
            try{
                listFile = file.listFiles();
                for (int i = 0; i < listFile.length; i++) {
                    f.add(listFile[i].getAbsolutePath());
                }
            }
            catch(Exception e){
                Log.i("File Error","No File Could be Created");
            }
        }
        else{
            Log.i("File Error","Filepath was not a directory");
        }

    }
    public void makeBitmaps(ArrayList<String> files){
        final BitmapFactory.Options options = new BitmapFactory.Options();
        for (int i = 0; i < files.size(); i ++){
            File imgFile = new File(files.get(i));
            if (imgFile.exists() && imgFile.canRead()){
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                options.inSampleSize = calculateInSampleSize(options,50,50);
                options.inJustDecodeBounds = false;
                images.add(BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options));
            }
        }
    }
    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) >= reqHeight
                    && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }


}

SlideActivity.java

package app.rpass;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

public class SlideActivity extends AppCompatActivity {



    ViewPager viewPager;
    CustomSwipeAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.swipe);
        viewPager = (ViewPager)findViewById(R.id.view_pager);

        int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE =1;

        if (ContextCompat.checkSelfPermission(SlideActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Log.i("Permissions Error","No permission inside of SlideActivity");
            ActivityCompat.requestPermissions(SlideActivity.this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);

        }

        adapter = new CustomSwipeAdapter(this);
        new AsyncTask<Void,Void,Void>(){
            ProgressDialog dialog = new ProgressDialog(SlideActivity.this);
            @Override
            protected void onPreExecute() {
                dialog.setMessage("Loading Data...");
                dialog.show();
            }

            @Override
            protected Void doInBackground(Void... voids) {
                adapter.getFromSdcard();
                adapter.makeBitmaps(adapter.f);
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                if (dialog.isShowing()){
                    dialog.dismiss();
                }
                viewPager.setAdapter(adapter);
                viewPager.getAdapter().notifyDataSetChanged();
            }
        }.execute();
        //adapter.getFromSdcard();
        //adapter.makeBitmaps(adapter.f);
        //viewPager.setAdapter(adapter);
        //viewPager.getAdapter().notifyDataSetChanged();
    }
}

Swipe.xml

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:tools="http://schemas.android.com/tools">



    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v4.view.ViewPager>


</RelativeLayout>

swipe_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/image_count"
        android:text=""
        android:textSize="25dp"
        android:textStyle="bold"
        android:gravity="center"
        android:layout_marginTop="25dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ImageView
        android:layout_marginTop="25dp"
        android:scaleType="fitXY"
        android:id="@+id/imageView2"
        android:layout_width="50dp"
        android:layout_height="50dp" />

</LinearLayout>

My issue is that the textViews are being created just fine, and are giving the appropriate filepaths, but the images are not appearing. I've searched many other examples and still can't figure out what I'm doing wrong. I'm sure that I've been working on it so much that I simply have overlooked something. Any input would be much appreciated. Thanks!

In swipe_layout.xml the root LinearLayout has default orientation of horizontal and its first child TextView layout_width is set to match_parent . Hence, the second child ImageView is not visible. If you set the root view's orientation to vertical you should be able to see the ImageView too!

Edit: Uploaded screenshot Android studio gives nice warning messages in these scenarios 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM