如何设置在3个不同的ImageView图像适配器列表,并把它上传

问题描述 投票:0回答:1

我对着在我所设置的图像到3个不同的imageview并上传一个问题,因为我必须显示适配器列表imageview我无法在适配器类由于对此我无法得到onActivityRessult的ID叫imageview

试着拨打onActivityResult在活动课,但imageviews的ID从适配器列表来

screenshot

当我上添加按钮,点击它会打开一个对话框,选择从相机或画廊形象,那么它应该能够在imageviews设置

编辑后:UploadAdapter.java

public class UploadAdapter extends RecyclerView.Adapter<UploadAdapter.UploadViewHolder> {

    private Callback mCallback;
    private Context ctx;
    private List<UploadModelClass> uploadModelClassList;

    public interface Callback {
        void showPictureDialog();
        void uploadMultipart();
    }

    public UploadAdapter(Context ctx, List<UploadModelClass> uploadModelClassList,Callback callback) {
        this.ctx = ctx;
        this.uploadModelClassList = uploadModelClassList;
        this.mCallback = callback;
    }

    @NonNull
    @Override
    public UploadViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LayoutInflater inflater=LayoutInflater.from(ctx);
        View view=inflater.inflate(R.layout.layout_upload_list,null);
        return new UploadViewHolder(view);
    }

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

        holder.txtv_item_code.setText(uploadModelClassList.get(position).getItem_code());
        holder.txtv_item_name.setText(uploadModelClassList.get(position).getItem_name());

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

                mCallback.showPictureDialog();

            }
        });

        holder.txtv_item_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallback.uploadMultipart();
            }
        });


        if(position %2 == 1)
        {
            holder.itemView.setBackgroundColor(Color.parseColor("#ffffff"));

        }
        else
        {
            holder.itemView.setBackgroundColor(Color.parseColor("#dddddd"));

        }

    }


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

    public class UploadViewHolder extends RecyclerView.ViewHolder {
        ImageView imageviewUpload,imageviewUpload2;
        TextView txtv_item_code,txtv_item_name,txtv_item_choose,txtv_item_image;


        public UploadViewHolder(@NonNull View itemView) {
            super(itemView);

            txtv_item_code=itemView.findViewById(R.id.txtv_layoutUploadList_item_code);
            txtv_item_name=itemView.findViewById(R.id.txtv_layoutUploadList_name);
            txtv_item_choose=itemView.findViewById(R.id.txtv_layoutUploadList_choose);
            txtv_item_image=itemView.findViewById(R.id.txtv_layoutUploadList_image);
            imageviewUpload=itemView.findViewById(R.id.imageview_layoutUploadList1);
            imageviewUpload2=itemView.findViewById(R.id.imageview_layoutUploadList2);

        }
    }
}

编辑后:UploadActivity

public class UploadActivity extends AppCompatActivity implements UploadAdapter.Callback {

    UploadAdapter uploadAdapter;
    RecyclerView recyclerView_upload;
    ArrayList<UploadModelClass> uploadModelClassArrayList;

    private int GALLERY = 1, CAMERA = 2,GALLERY2 = 3;
    Uri filePath;
    private static final String IMAGE_DIRECTORY = "/abcipl";

    ImageView imageView,imageView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        requestMultiplePermissions();

       // ProductAdapter productAdapter=new ProductAdapter();
        uploadModelClassArrayList=new ArrayList<>();
        recyclerView_upload = findViewById(R.id.recycler_view_upload_activity);


      /*  imageView=findViewById(R.id.testttt);
        imageView2=findViewById(R.id.testttt2);*/


        uploadModelClassArrayList.add(new UploadModelClass("123445","Bulb"));
        uploadModelClassArrayList.add(new UploadModelClass("123445","Bulb"));
        uploadModelClassArrayList.add(new UploadModelClass("123445","Bulb"));
        uploadModelClassArrayList.add(new UploadModelClass("123445","Bulb"));


        recyclerView_upload.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        uploadAdapter = new UploadAdapter(this, uploadModelClassArrayList,UploadActivity.this);
        recyclerView_upload.setAdapter(uploadAdapter);

    }

    private void  requestMultiplePermissions(){
        Dexter.withActivity(this)
                .withPermissions(
                        Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        // check if all permissions are granted
                        if (report.areAllPermissionsGranted()) {
                            //Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
                        }

                        // check for permanent denial of any permission
                        if (report.isAnyPermissionPermanentlyDenied()) {
                            // show alert dialog navigating to Settings
                            //openSettingsDialog();
                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).
                withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
                    }
                })
                .onSameThread()
                .check();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        onBackPressed();
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == this.RESULT_CANCELED) {
            return;
        }
        if (requestCode == GALLERY) {
            if (data != null) {
                filePath = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(UploadActivity.this.getContentResolver(), filePath);
                    String path = saveImage(bitmap);
                    Toast.makeText(UploadActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
                    //imageviewUpload.setImageBitmap(bitmap);


                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(UploadActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
                }
            }

        }

       else if (requestCode == GALLERY2) {
            if (data != null) {
                filePath = data.getData();
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(UploadActivity.this.getContentResolver(), filePath);
                    String path = saveImage(bitmap);
                    Toast.makeText(UploadActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
                    //imageviewUpload.setImageBitmap(bitmap);



                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(UploadActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
                }
            }

        }


        else if (requestCode == CAMERA) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
           // imageviewUpload.setImageBitmap(thumbnail);
            //imageView.setImageBitmap(thumbnail);
            saveImage(thumbnail);
            Toast.makeText(UploadActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
        }
    }

    public String saveImage(Bitmap myBitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
        File wallpaperDirectory = new File(
                Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
        // have the object build the directory structure, if needed.
        if (!wallpaperDirectory.exists()) {
            wallpaperDirectory.mkdirs();
        }

        try {
            File f = new File(wallpaperDirectory, Calendar.getInstance()
                    .getTimeInMillis() + ".jpg");
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
            MediaScannerConnection.scanFile(UploadActivity.this,
                    new String[]{f.getPath()},
                    new String[]{"image/jpeg"}, null);
            fo.close();
            Log.d("TAG", "File Saved::---&gt;" + f.getAbsolutePath());

            return f.getAbsolutePath();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";
    }



    @Override
    public void showPictureDialog() {
        AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
        pictureDialog.setTitle("Select Action");
        String[] pictureDialogItems = {
                "Select photo from gallery",
                "Capture photo from camera" };
        pictureDialog.setItems(pictureDialogItems,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                choosePhotoFromGallery();
                                break;
                            case 1:
                                takePhotoFromCamera();
                                break;
                        }
                    }
                });
        pictureDialog.show();

    }

    /*
     * This is the method responsible for image upload
     * We need the full image path and the name for the image in this method
     * */
    @Override
    public void uploadMultipart() {
        //getting name for the image
        // String name = editTextImgName.getText().toString().trim();

        //getting the actual path of the image
        String path = getPath(filePath);

        //Uploading code
        try {
            String uploadId = UUID.randomUUID().toString();

            //Creating a multi part request
            new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
                    .addFileToUpload(path, "image") //Adding file
                    //.addParameter("name", name) //Adding text parameter to the request
                    .setNotificationConfig(new UploadNotificationConfig())
                    .setMaxRetries(2)
                    .startUpload(); //Starting the upload

        } catch (Exception exc) {
            Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    //method to get the file path from uri
    public String getPath(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();

        return path;
    }

    public void choosePhotoFromGallery() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(galleryIntent, GALLERY);
    }

    private void takePhotoFromCamera() {
        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, CAMERA);
    }
}

layout_upload_list.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">



    <LinearLayout
        android:id="@+id/linear_layoutUploadList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="5">

        <TextView
            android:id="@+id/txtv_layoutUploadList_item_code"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Item Code"
            android:textSize="14sp"
            android:textAlignment="center"
            android:layout_gravity="center"
            android:layout_weight="1"/>

        <TextView
            android:id="@+id/txtv_layoutUploadList_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Item Name"
            android:textSize="14sp"
            android:textAlignment="center"
            android:layout_gravity="center"
            android:padding="5dp"

            android:layout_weight="1"/>

        <TextView
            android:id="@+id/txtv_layoutUploadList_status"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Status"
            android:textSize="14sp"
            android:textAlignment="center"
            android:layout_gravity="center"
            android:padding="5dp"
            android:layout_weight="1"/>

        <ImageView
            android:id="@+id/imageview_layoutUploadList1"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:background="@color/monsoon"
            android:layout_marginBottom="5dp"
            android:layout_gravity="center"
            android:layout_marginTop="5dp"
            />
        <ImageView
            android:id="@+id/imageview_layoutUploadList2"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:background="@color/monsoon"
            android:layout_marginBottom="5dp"
            android:layout_gravity="center"
            android:layout_marginLeft="2dp"
            android:layout_marginTop="5dp"
            />
        <ImageView
            android:id="@+id/imageview_layoutUploadList3"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:background="@color/monsoon"
            android:layout_marginBottom="5dp"
            android:layout_gravity="center"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="5dp"
            />

        <TextView
            android:id="@+id/txtv_layoutUploadList_choose"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_add_blue"
            android:textAlignment="center"
            android:layout_gravity="center"

            android:layout_weight="1"

            android:layout_marginRight="5dp"
            />

        <!--<ImageView
            android:id="@+id/imageview_layoutUploadList"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@color/monsoon"
            android:layout_marginBottom="5dp"
            />-->

        <TextView
            android:id="@+id/txtv_layoutUploadList_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_upload_blue"
            android:textAlignment="center"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:layout_marginRight="5dp"/>


    </LinearLayout>

</RelativeLayout>
android android-recyclerview image-uploading android-adapter
1个回答
0
投票

这里是Adapter应该如何与Activity沟通。

public class SomeActivity extends AppCompatActivity
        implements SomeAdapter.Callback {
    ArrayList<String> imagesUris1 = new ArrayList();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.layout_file);

        SomeAdapter adapter = new SomeAdpter(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //calling saveImage()
    }

    public String saveImage(Bitmap myBitmap) {
        try{
            //...getting file uri
            imageUris1.add(f.getAbsolutePath());
            adapter.setFirstImageUris(imageUris1);
            return f.getAbsolutePath(); //Ignored
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return "";
    }

    //..Other activity related stuff

    @Override
    void showImageDialog() {
      //Open gallary or camera from here
    }
}

public class SomeAdpter extends RecyclerView.Adapter<SomeAdapter.SomeHolder> {
  Callback callback;
  ArrayList<String> firstImageUris, secondImageUris, thirdImagesUris = new ArrayList();

  public SomeAdapter(Callback callback) {
    this.callback = callback;
    firstImageUris = new ArrayList();
    for(int i=0; i<uploadModelClassList.size(); i++) {
        firstImageUris.add("");
    }
  }
  //Adapter related methods, call callback.showImageDialog() in onBindViewHolder
  @Override
  public void onBindViewHolder(@NonNull UploadViewHolder holder, final int position) {
      //Use uri arraylist to show image in imageview.
      holder.imageviewUpload.setImageURI(firstImageUris.get(position));
  }

  public void setFirstImageUris(ArrayList<String> imagesUris) {
      this.firstImageUris = imageUris;
      notifyDataSetChanged();
  }
  //Similar methods to store 2nd and 3rd image uris.

  public interface Callback {
    void showImageDialog();
  }
}

您不理你保存图像的absoluteFilePath。使arraylistactivity保存并把它传递给adapter。活动不必知道imageview的ID,它只是将数据传递到适配器。适配器应notifyDataSetChanged更新自己。我已经添加了一些虚拟代码,以帮助您与第一形象,你必须为第2和第3位的图像做相同的。

你必须写自己的处理图像索引和URI列表的逻辑。添加一些示例代码,以帮助你一点。

//Initialize uri lists with uploadModelClassArrayList so that they have same size
    for (int i = 0; i < 4; i++) {
            uploadModelClassArrayList.add(new UploadModelClass("123445", "Bulb"));
            imagesUris1.add("");
            imagesUris2.add("");
            imagesUris3.add("");
        }

//Pass lists to the adapter constructor
    uploadAdapter = new UploadAdapter(this, uploadModelClassArrayList, imagesUris1,
                imagesUris2, imagesUris3, UploadActivity.this);

//Initialize adapter lists
    public UploadAdapter(Context ctx, List<UploadModelClass> uploadModelClassList,
                ArrayList<String> firstImagelist, ArrayList<String> secondImagelist,
                ArrayList<String> thirdImagelist, Callback callback) {
            this.ctx = ctx;
            this.firstImageUris = firstImagelist;
            this.secondImageUris = secondImagelist;
            this.thirdImagesUris = thirdImagelist;
            this.uploadModelClassList = uploadModelClassList;
            this.mCallback = callback;
    }
© www.soinside.com 2019 - 2024. All rights reserved.