简体   繁体   中英

Image is displaying in only 1st item in gridview

Image is displaying in only first item in gridview. Below is my GridImageActivity where i am taking the image either from gallery or capturing it from camera. After taking the image, image is setting in only first item of gridview. How can I display the image in different items of gridview. Any help is appreciated. Thanks in advance.

 public class GridImage extends AppCompatActivity {
        GridView gv_gridimg;
        private Context context = this;
        Activity  activity;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_grid_image);
            gv_gridimg = findViewById(R.id.gv_gridimg);
            GridImgAdapter gridImgAdapter = new GridImgAdapter(this);
            gv_gridimg.setAdapter(gridImgAdapter);

                gv_gridimg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        // gridImgAdapter.notifyDataSetChanged();  //to clear all the data that is assigned
                        String[] galleryPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

                        if (EasyPermissions.hasPermissions(context, galleryPermissions)) {
                            pickImageFromGallery();
                        } else {
                            EasyPermissions.requestPermissions(activity, "Access for storage", 101, galleryPermissions);
                        }
                    }
                });
            }


        private void pickImageFromGallery() {
            final CharSequence[] options = {"Take photo", "Choose from gallery", "Cancel"};
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle("Choose your profile picture");
            builder.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Take photo")) {
                        Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(takePicture, 0);
                    } else if (options[item].equals("Choose from gallery")) {
                        Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(pickPhoto, 1);
                    } else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
        @Override
        protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            ImageView iv_gridimg = (ImageView) gv_gridimg.findViewById(R.id.iv_gridimg);

            if (resultCode != RESULT_CANCELED) {
                switch (requestCode) {
                    case 0:
                        if (resultCode == RESULT_OK && data != null) {
                            Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
                             iv_gridimg.setImageBitmap(selectedImage);

                        }
                        break;
                    case 1:
                        if (resultCode == RESULT_OK && data != null) {
                            Uri selectedImage = data.getData();
                            String[] filePathColumn = new String[]{MediaStore.Images.Media.DATA};
                            if (selectedImage != null) {
                                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                                if (cursor != null) {
                                    cursor.moveToFirst();
                                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                                    String picturesPath = cursor.getString(columnIndex);
                                    iv_gridimg.setImageBitmap(BitmapFactory.decodeFile(picturesPath));
                                    cursor.close();
                                }
                            }
                        }
                        break;
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

This is my adapter class

public class GridImgAdapter extends BaseAdapter {
    private Context context;
    public GridImgAdapter(Context context) {
        this.context  = context;
    }

    @Override
    public int getCount() {
        return 4;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }
    @Override
    public boolean isEnabled(int position) {
        return true;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View gv_gridimg;
        gv_gridimg = layoutInflater.inflate(R.layout.item_grid_img,null);
        ImageView iv_gridimg = (ImageView) gv_gridimg.findViewById(R.id.iv_gridimg);
        return gv_gridimg;
    }
}

This is my main xml file

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activity.GridImage">
    <GridView
        android:id="@+id/gv_gridimg"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true"
        android:numColumns="2"/>
</RelativeLayout>

This is my item xml file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ImageView
        android:id="@+id/iv_gridimg"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:padding="40dp"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:src="@drawable/ic_camera_black_24dp"/>
</RelativeLayout>

In item.xml change height and width of parent layout to wrap_content because you are set as match_parent so, it's shows in whole screen.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/iv_gridimg"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:padding="40dp"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:src="@drawable/ic_camera_black_24dp"/>
</RelativeLayout>

I hope this can help you!

Thank You.

Your adapter doesn't contain any data to show, you should add an ArrayList of data to constructor of the adapter like this:

public GridImgAdapter(Context context, ArrayList images) { this.context = context; this.images = images; }

then in the getView() method you need to set the data to your ImageView like this:

ImageView iv_gridimg = (ImageView) gv_gridimg.findViewById(R.id.iv_gridimg); iv_gridimg.setImageResource(images.get(position));

You can't use findViewById always because it's always return first item in list. You have to hold your bitmaps in adapter with positions for display.

public class GridImgAdapter extends BaseAdapter {
HashMap<Integer, Bitmap> images = new HashMap<>();

    public void putImage(int position, Bitmap bitmap) {
        images.put(position, bitmap);
        notifyDataSetChanged()
    }

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View gv_gridimg;
    gv_gridimg = layoutInflater.inflate(R.layout.item_grid_img,null);
    ImageView iv_gridimg = (ImageView) gv_gridimg.findViewById(R.id.iv_gridimg);
       if(images.get(position)!=null) iv_gridimg.setImageBitmap(images.get(position);
    return gv_gridimg;
}
   ...

declare variable for current selected position in grid

 int selectedPosition;
 gv_gridimg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    selectedPosition=position;

OnActivityReult:

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


        if (resultCode != RESULT_CANCELED) {
            switch (requestCode) {
                case 0:
                    if (resultCode == RESULT_OK && data != null) {
                        Bitmap selectedImage = (Bitmap) data.getExtras().get("data");
                        //call adapter putImage method

                    }
                    break;
                case 1:
                    if (resultCode == RESULT_OK && data != null) {
                        Uri selectedImage = data.getData();
                        String[] filePathColumn = new String[]{MediaStore.Images.Media.DATA};
                        if (selectedImage != null) {
                            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                            if (cursor != null) {
                                cursor.moveToFirst();
                                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                                String picturesPath = cursor.getString(columnIndex);
                                //call adapter putImage method

                            }
                        }
                    }
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM