动态地将两种不同的布局添加到回收器视图中

时间:2016-10-06 06:01:21

标签: android

我有两个布局1)用于图像,2)用于文档  在MainActivity by option菜单中,我从设备存储中选择image或pdf,然后使用pojo类将数据发送到适配器类。

我的问题是我无法在回收站视图中正确绑定这些布局我希望像我选择图像时那样会在回收器视图中显示,而在同一列表中也会显示相同的pdf文件视图。

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 个答案:

答案 0 :(得分:0)

在你的pojo中添加一个变量,告诉你将实现哪个布局。

答案 1 :(得分:0)

将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 :(得分:0)

创建一个适配器,在用户选择任何内容时更新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();

            }
    }
}
}