将图像从 Phone 上传到 RecyclerView GridView

Uploading Image from Phone to RecyclerView GridView

我正在尝试使用滑行来执行此操作。我有一个 Gridview 回收器视图,回收器中已有 9 张图片。实现了一个 OnClickListener,它将我带到 phone 的画廊,这样我就可以将图像上传到 Recycler 视图中。当我使用 mLayoutManager.findViewByPosition(imagePosition) 时出现问题。 Glide 需要一个 imageView,但是 layoutmanager returns 一个 CardView?来自 Recycler View 中每个项目的自定义 XML。确切地说,我该怎么做呢?谢谢!!

错误:

E/libc: Access denied finding property "vendor.gralloc.disable_ahardware_buffer"
W/Glide: Failed to find GeneratedAppGlideModule. You should include an annotationProcessor compile dependency on com.github.bumptech.glide:compiler in your application and a @GlideModule annotated AppGlideModule implementation or LibraryGlideModules will be silently ignored
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.imagegridactivity, PID: 25530
    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { {com.example.imagegridactivity/com.example.imagegridactivity.MainActivity}: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4845)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4886)
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.ClassCastException: androidx.cardview.widget.CardView cannot be cast to android.widget.ImageView
        at com.example.imagegridactivity.MainActivity.onActivityResult(MainActivity.java:128)
        at android.app.Activity.dispatchActivityResult(Activity.java:8135)
        at android.app.ActivityThread.deliverResults(ActivityThread.java:4838)
        at android.app.ActivityThread.handleSendResult(ActivityThread.java:4886) 
        at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
        at android.os.Handler.dispatchMessage(Handler.java:107) 
        at android.os.Looper.loop(Looper.java:214) 
        at android.app.ActivityThread.main(ActivityThread.java:7356) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
I/Process: Sending signal. PID: 25530 SIG: 9
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'

适配器:

public class AnimalsAdapter extends RecyclerView.Adapter<AnimalsAdapter.ViewHolder> {

    ImageView imageView;

    private Uri imageUri;
    private ArrayList<animal_item> mDataSet;
    private Context mContext;
    private OnItemClickListener mListener;

    public ArrayList<animal_item> getDataSet() {
        return mDataSet;
    }

    public void setDataSet(ArrayList<animal_item> mDataSet) {
        this.mDataSet = mDataSet;
    }

    public ImageView getImageView() {
        return imageView;
    }

    public void setImageView(ImageView imageView) {
        this.imageView = imageView;
    }

    public Context getContext() {
        return mContext;
    }

    public void setContext(Context mContext) {
        this.mContext = mContext;
    }

    public Uri getImageUri() {
        return imageUri;
    }

    public void setImageUri(Uri imageUri) {
        this.imageUri = imageUri;
    }

    public interface OnItemClickListener {

        void onItemClick(int position);

    }

    public void setOnItemClickListener(OnItemClickListener listener) {

        mListener = listener;

    }

    public AnimalsAdapter(Context context, ArrayList<animal_item> DataSet) {
        mDataSet = DataSet;
        mContext = context;
    }

    public ArrayList<animal_item> DataSet() {

        return mDataSet;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView mImageView;
        public LinearLayout mLinearLayout;

        public ViewHolder(View v, final OnItemClickListener listener) {
            super(v);

            mImageView = (ImageView) v.findViewById(R.id.tv);

            mImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (listener != null) {

                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) ;
                        listener.onItemClick(position);
                    }
                }
            });
            mLinearLayout = (LinearLayout) v.findViewById(R.id.ll);
        }



        public ImageView getImageView() {

            return mImageView;
        }

        public void setImageView(ImageView mImageView) {

            this.mImageView = mImageView;
        }
    }

    @Override
    public AnimalsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // Create a new View
        View v = LayoutInflater.from(mContext).inflate(R.layout.custom_view, parent, false);
        ViewHolder vh = new ViewHolder(v, (OnItemClickListener) mListener);
        return vh;
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {

        final animal_item animalItem = mDataSet.get(position);

        holder.mImageView.setImageResource(animalItem.getImageResource());

        imageView = holder.mImageView;

    }

    @Override
    public int getItemCount() {

        return mDataSet.size();
    }

}

个人观点:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    card_view:cardCornerRadius="4dp"
    card_view:cardElevation="2dp"
    card_view:cardMaxElevation="4dp"
    card_view:contentPadding="5dp">

    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="3dp">

        <ImageButton
            android:id="@+id/tv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_margin="2dp"
            android:gravity="center"
            android:padding="10dp"
            android:textColor="#000"
            android:textSize="25dp"
            android:textStyle="bold" />

    </LinearLayout>
</androidx.cardview.widget.CardView>

主要Activity:

public class MainActivity extends AppCompatActivity {
    private Context mContext;

    RelativeLayout mRelativeLayout;
    private RecyclerView mRecyclerView;
    private AnimalsAdapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private ArrayList<animal_item> arrayList;
    private Uri imageUri;

    private int imagePosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        mContext = getApplicationContext();


        getSupportActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#FF677589"))
        );

        mRelativeLayout = findViewById(R.id.rl);
        mRecyclerView = findViewById(R.id.recycler_view);

        final int[] imageArray = new int[9];

        for (int i = 0; i < imageArray.length; i++) {

            imageArray[i] = R.mipmap.pic1_foreground;

        }

        arrayList = new ArrayList<>();

        for (int i = 0; i < imageArray.length; i++) {

            int image = imageArray[i];
            arrayList.add(new animal_item(image));

        }

        mLayoutManager = new GridLayoutManager(mContext, 3);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mAdapter = new AnimalsAdapter(mContext, arrayList);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new AnimalsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {

                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, 1);

            }
        });

        ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT, 0) {

            final ArrayList aL = new ArrayList<>();

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder dragged, @NonNull RecyclerView.ViewHolder target) {

                int position_dragged = dragged.getAdapterPosition();
                int position_target = target.getAdapterPosition();

                Collections.swap(arrayList, position_dragged, position_target);
                mAdapter.notifyItemMoved(position_dragged, position_target);
                //Collections.copy(mQuestion11List, aL);

                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {

            }
        });

        helper.attachToRecyclerView(mRecyclerView);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        imageUri = data.getData();

        //mAdapter.getDataSet().get(imagePosition).setImageResource();
        Glide.with(MainActivity.this).load(imageUri).into(mLayoutManager.findViewByPosition(imagePosition));

    }
}

单个项目:

package com.example.imagegridactivity;

public class animal_item {

    private int imageResource;

    public animal_item(int imageResource) {
        this.imageResource = imageResource;
    }

    public int getImageResource() {
        return imageResource;
    }

    public void setImageResource(int imageResource) {
        this.imageResource = imageResource;
    }
}

方法mLayoutManager.findViewByPosition(imagePosition) return表示相应适配器位置的视图。您必须在 returned 视图上使用 findViewById(R.id.tv) 来获取图像视图并将其作为目标传递给 glide。