Oreo ViewPager 显示来自外部存储文件路径的图像

Oreo ViewPager to display images from external storage filepaths

所以我对 Java 和 Android 都很陌生,正在为一个项目开发应用程序。在该应用程序中,我希望拥有自己的图片库/查看器,专门用于我们将使用该应用程序保存的图像。因此,我想使用 ViewPager 来滑动图像,并创建了一个自定义寻呼机适配器。以下是相关文件:

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>

我的问题是 textView 创建得很好,并提供了适当的文件路径,但图像没有出现。我已经搜索了许多其他示例,但仍然无法弄清楚我做错了什么。我确信我一直在努力,以至于我只是忽略了一些东西。任何输入将不胜感激。谢谢!

swipe_layout.xml 中,根 LinearLayout 的默认方向为 horizontal,其第一个 child TextView layout_width 设置为 match_parent。因此,第二个 child ImageView 不可见。如果您将根视图的方向设置为垂直,您应该也能看到 ImageView

编辑:上传截图 Android studio 在这些情况下给出了很好的警告信息