Динамическое добавление двух различных макетов в представление recycler

У меня есть два макета 1) для изображения и 2) для документа
В меню опций MainActivity by я выбираю изображение или pdf из хранилища устройства и отправляю данные в класс адаптера с помощью класса pojo.

Моя проблема заключается в том, что я не могу связать эти макеты должным образом в recycler view я хочу что-то вроде, Когда я выбираю изображение, чем он будет показан в recycler view и так же, как pdf-файл view также в том же списке.

public class HirenModifided extends AppCompatActivity {
    private Dialog dialog;
    private RecyclerView recyclerView;
    SetterGetter setGet;

    public static final int RESULT_LOAD_FILE = 0;
    public static final int RESULT_LOAD_IMAGE = 1;
    public static final int RESULT_OK = -1;
    public static final int REQUEST_IMAGE_CAPTURE = 2;
    private ImageAdapter objAdapter;
    public static ArrayList<SetterGetter> pdfPaths = new ArrayList<>();
    public static ArrayList<SetterGetter> imagePaths = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        setGet = new SetterGetter();

        recyclerView.setHasFixedSize(true);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(mLayoutManager);
        objAdapter = new ImageAdapter(getApplicationContext());
        recyclerView.setAdapter(objAdapter);


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.image:
                itemAddClick();
                return true;
            case R.id.file:
                FilePicker();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    public void FilePicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        startActivityForResult(intent, RESULT_LOAD_FILE);
    }


    public void itemAddClick() {
        dialog = new Dialog(HirenModifided.this);
        dialog.setContentView(R.layout.custom_dialog_box);
        dialog.setTitle("Select Photo");

        Button btnExit = (Button) dialog.findViewById(R.id.btnExit);
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.findViewById(R.id.btnChoosePath).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activeGallery();
            }
        });
        dialog.findViewById(R.id.btnTakePhoto).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activeTakePhoto();
            }
        });

        // show dialog on screen
        dialog.show();
    }

    private void activeGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, RESULT_LOAD_IMAGE);
        dialog.dismiss();
    }

    private void activeTakePhoto() {

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        dialog.dismiss();

    }


    //this method is for resize image
    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();

        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {

            case RESULT_LOAD_IMAGE:
                if (requestCode == RESULT_LOAD_IMAGE &&
                        resultCode == RESULT_OK && null != data) {
                    Uri filePath = data.getData();
                    Log.e("IMAGE", filePath + "");

                    try {
                        InputStream imageStream = this.getContentResolver().openInputStream(filePath);
                        Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        selectedImage = getResizedBitmap(selectedImage, 400);
                        selectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);

                        byte[] byteArray = stream.toByteArray();
                       /* setGet.path(Base64.encodeToString(byteArray, Base64.DEFAULT));
                        imagePaths.add(setGet);
                        //FilePaths.clear();
                        FilePaths.addAll(imagePaths);
                        objAdapter.notifyDataSetChanged();*/
                        setGet.path(Base64.encodeToString(byteArray, Base64.DEFAULT));
                        imagePaths.add(setGet);
                        objAdapter.insert(imagePaths);


                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }


            case RESULT_LOAD_FILE:
                if (requestCode == RESULT_LOAD_FILE &&
                        resultCode == RESULT_OK && null != data) {
                    String FilePath = data.getData().getPath();
                    Log.e("FILEPATH", FilePath);
                    String filename = FilePath.substring(FilePath.lastIndexOf("/") + 1);
                    Log.e("onActivityResult: ", filename);

                    /*  setGet.path(filename);
                  pdfPaths.add(setGet);
                    //FilePaths.clear();
                    FilePaths.addAll(pdfPaths);
                    objAdapter.notifyDataSetChanged();*/

                    setGet.path(filename);
                    pdfPaths.add(setGet);
                    objAdapter.insert(pdfPaths);
                }
        }


    }


}

Pojo

public class SetterGetter {
    public static String path;


    public void path(String s) {
        path = s;
    }

    public String getPath() {
        return path;
    }


}

Адаптер

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> {
    private LayoutInflater inflater = null;

    public static ArrayList<SetterGetter> file_paths = new ArrayList<>();

    public static final int RESULT_LOAD_FILE = 0;
    public static final int RESULT_LOAD_IMAGE = 1;

    int get_list_position;

    Context context;

    public ImageAdapter(Context mcontext) {
        this.context = mcontext;
        inflater = LayoutInflater.from(context);
    }


    public class ViewHolder extends RecyclerView.ViewHolder {
        public ViewHolder(View itemView) {
            super(itemView);
        }

    }

    public class FilePick extends ViewHolder {
        TextView temp;

        public FilePick(View v) {
            super(v);
            this.temp = (TextView) v.findViewById(R.id.file_name);
        }
    }

    public class ImagePick extends ViewHolder {
        ImageView score;

        public ImagePick(View v) {
            super(v);
            this.score = (ImageView) v.findViewById(R.id.image_list);
        }

    }

    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }

    // Insert a new item to the RecyclerView on a predefined position
    public void insert(ArrayList<SetterGetter> data) {

        file_paths.add(data.get(get_list_position));
        notifyItemInserted(get_list_position);
    }

   /* // Remove a RecyclerView item containing a specified Data object
    public void remove(SetterGetter data) {
        int position = file_paths.indexOf(data);
        file_paths.remove(position);
        Toast.makeText(context, "Deleted : " + position, Toast.LENGTH_SHORT).show();
        notifyItemRemoved(position);
    }*/


    @Override
    public int getItemViewType(int position) {

        // Log.e("getItemViewType:pos ", String.valueOf(position));
        Log.e("IS this PDF ?", String.valueOf(file_paths.get(position).getPath().endsWith(".pdf")));
        if (file_paths.get(position).getPath().endsWith("pdf")) {
            return RESULT_LOAD_FILE;
        } else {
            return RESULT_LOAD_IMAGE;
        }
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v;

        Log.e("layout code: ", viewType + "");

        if (viewType == RESULT_LOAD_FILE) {
            v = inflater
                    .inflate(R.layout.file_raw, parent, false);
            return new FilePick(v);
        } else {
            v = inflater
                    .inflate(R.layout.raw, parent, false);
            return new ImagePick(v);
        }


    }

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


        Log.e("onBindViewHolder:pos ", String.valueOf(position));
        get_list_position = position;

        if (holder instanceof FilePick) {
            FilePick file = (FilePick) holder;
            file.temp.setText(file_paths.get(position).getPath());

        } else if (holder instanceof ImagePick) {
            ImagePick image = (ImagePick) holder;
            byte[] decodeValue = new byte[0];
            try {
                decodeValue = Base64.decode(file_paths.get(position).getPath().getBytes("UTF-8"), Base64.DEFAULT);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Bitmap bitmap = BitmapFactory.decodeByteArray(decodeValue, 0, decodeValue.length);
            image.score.setImageBitmap(bitmap);
        }
    }

    @Override
    public int getItemCount() {
        return file_paths.size();
    }

}

3 ответа

  1. изменение onBindViewHolder на

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
    
    
        Log.e("onBindViewHolder:pos ", String.valueOf(position));
        if (holder instanceof FilePick) {
            FilePick file = (FilePick) holder;
            file.temp.setText(Data.get(position).getPath());
    
        } else if (holder instanceof ImagePick) {
            ImagePick image = (ImagePick) holder;
            byte[] decodeValue = new byte[0];
            try {
                decodeValue = Base64.decode(Data.get(position).getPath().getBytes("UTF-8"), Base64.DEFAULT);
                Log.e("4", decodeValue + "");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Bitmap bitmap = BitmapFactory.decodeByteArray(decodeValue, 0, decodeValue.length);
            image.score.setImageBitmap(bitmap);
        }
    }
    

    могут помочь вам.

  2. Создайте один адаптер, обновите Dataпеременную, когда пользователь выбирает что-либо и вызывает notifyDataSetChangedметод.

    public class MainActivity extends AppCompatActivity {
    
    private Dialog dialog;
    private RecyclerView recyclerView;
    ImageAdapter objImageAdapter;
    ArrayList<SetterGetter> FilePaths;
    ArrayList<SetterGetter> imagePaths;
    ArrayList<SetterGetter> pdfPaths;
    SetterGetter setGet;
    
    public static final int RESULT_LOAD_FILE = 0;
    public static final int RESULT_LOAD_IMAGE = 1;
    public static final int RESULT_OK = -1;
    public static final int REQUEST_IMAGE_CAPTURE = 2;
    private ImageAdapter objAdapter;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        setGet = new SetterGetter();
        FilePaths = new ArrayList<SetterGetter>();
        recyclerView.setLayoutManager(mLayoutManager);
    
                        objAdapter = new ImageAdapter(getApplicationContext(), FilePaths);
                        recyclerView.setAdapter(objAdapter);
    
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.image:
                itemAddClick();
                return true;
            case R.id.file:
                FilePicker();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    public void FilePicker() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("*/*");
        startActivityForResult(intent, RESULT_LOAD_FILE);
    }
    
    
    public void itemAddClick() {
        dialog = new Dialog(MainActivity.this);
        dialog.setContentView(R.layout.custom_dialog_box);
        dialog.setTitle("Select Photo");
    
        Button btnExit = (Button) dialog.findViewById(R.id.btnExit);
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.findViewById(R.id.btnChoosePath).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activeGallery();
            }
        });
        dialog.findViewById(R.id.btnTakePhoto).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                activeTakePhoto();
            }
        });
    
        // show dialog on screen
        dialog.show();
    }
    
    private void activeGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, RESULT_LOAD_IMAGE);
        dialog.dismiss();
    }
    
    private void activeTakePhoto() {
    
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        dialog.dismiss();
    
    }
    
    //Read Shared Images
    
    //this method is for resize image
    public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
        int width = image.getWidth();
        int height = image.getHeight();
    
        float bitmapRatio = (float) width / (float) height;
        if (bitmapRatio > 1) {
            width = maxSize;
            height = (int) (width / bitmapRatio);
        } else {
            height = maxSize;
            width = (int) (height * bitmapRatio);
        }
        return Bitmap.createScaledBitmap(image, width, height, true);
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
    
            case RESULT_LOAD_IMAGE:
                if (requestCode == RESULT_LOAD_IMAGE &&
                        resultCode == RESULT_OK && null != data) {
                    Uri filePath = data.getData();
                    Log.e("IMAGE", filePath + "");
    
                    try {
                        InputStream imageStream = this.getContentResolver().openInputStream(filePath);
                        Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
                        ByteArrayOutputStream stream = new ByteArrayOutputStream();
                        selectedImage = getResizedBitmap(selectedImage, 400);
                        selectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
    
                        byte[] byteArray = stream.toByteArray();
                        setGet.path(Base64.encodeToString(byteArray, Base64.DEFAULT));
                        imagePaths.add(setGet);
                        //Log.e("IMAGE",FilePaths+"");
                        FilePaths.clear();
                        FilePaths.addAll(imagePaths);
                        objAdapter.notifyDataSetChanged();
    
    
    
    
    
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
    
                }
    
    
            case RESULT_LOAD_FILE:
                if (requestCode == RESULT_LOAD_FILE &&
                        resultCode == RESULT_OK && null != data) {
                    String FilePath = data.getData().getPath();
                    Log.e("FILEPATH", FilePath);
                    String filename =               FilePath.substring(FilePath.lastIndexOf("/") + 1);
                    Log.e("onActivityResult: ", filename);
                    setGet.path(filename);
                    FilePaths.add(setGet);
                   pdfPaths.add(setGet);
                        //Log.e("IMAGE",FilePaths+"");
                        FilePaths.clear();
                        FilePaths.addAll(pdfPaths);
                        objAdapter.notifyDataSetChanged();
    
                }
        }
    }
    }