vendredi 31 mars 2017

Android: Implement Select all checkbox in gridview with checkbox and imageview

I want to make custom gallery with image and checkbox, user can select single image by selecting individual checkbox of image and also i have checkall functionality to select all the checkbox in the gridview.

I have implemented ViewHolder class for custom gridview

here is my code:

public class MainActivity extends AppCompatActivity {

private int count;
private Bitmap[] thumbnails;
private boolean[] thumbnailsselection;
private String[] arrPath;
private ImageAdapter imageAdapter;
CheckBox chkSelectAll;

GridView imagegrid;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    chkSelectAll= (CheckBox) findViewById(R.id.chkSelectAll);
     imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);




    final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    Cursor imagecursor = managedQuery(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.thumbnails = new Bitmap[this.count];
    this.arrPath = new String[this.count];
    this.thumbnailsselection = new boolean[this.count];
    for (int i = 0; i < this.count; i++) {
        imagecursor.moveTo`enter code here`Position(i);
        int id = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                getApplicationContext().getContentResolver(), id,
                MediaStore.Images.Thumbnails.MICRO_KIND, null);
        arrPath[i]= imagecursor.getString(dataColumnIndex);
    }
    imageAdapter = new ImageAdapter();
    imageAdapter.notifyDataSetChanged();
    imagegrid.setAdapter(imageAdapter);
   // imagecursor.close();
    findViewById(R.id.chkSelectAll).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           /* ViewHolder vh=new ViewHolder();
            for (int i = 0; i < imagegrid.getCount() ; i++ ){
                View view = imagegrid.getChildAt(i);
                if(view != null) {
                    vh.checkbox = (CheckBox) view.findViewById(R.id.itemCheckBox);
                    vh.checkbox.setChecked(true);
                }
            }*/

           int count = imagegrid.getAdapter().getCount();
            for (int i = 0; i < count; i++) {
                RelativeLayout itemLayout = (RelativeLayout)imagegrid.getChildAt(i); // Find by under LinearLayout

                Log.e("", "onClick: "+itemLayout );
                CheckBox checkbox = (CheckBox)itemLayout.findViewById(R.id.itemCheckBox);
                checkbox.setChecked(true);
            }



        }
    });
}



public void selectedImage()
{
    final int len = thumbnailsselection.length;
    int cnt = 0;
    String selectImages = "";
    for (int i =0; i<len; i++)
    {
        if (thumbnailsselection[i]){
            cnt++;
            selectImages = selectImages + arrPath[i] + "|";
        }
    }
    if (cnt == 0){
        Toast.makeText(getApplicationContext(),
                "Please select at least one image",
                Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(),
                "You've selected Total " + cnt + " image(s).",
                Toast.LENGTH_LONG).show();
        Log.d("SelectedImages", selectImages);
    }
}
public class ImageAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    public ImageAdapter() {
        mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    }

    public int getCount() {
        return count;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(
                    R.layout.galleryitem, null);
            holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
            holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);

            convertView.setTag(holder);
        }
        else {
            holder = (ViewHolder) convertView.getTag();
        }


        holder.checkbox.setId(position);
        holder.imageview.setId(position);
        holder.checkbox.setOnClickListener(new View.OnClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public void onClick(View v) {
                // TODO Auto-generated method stub
               CheckBox cb = (CheckBox) v;
                int id = cb.getId();
                if (thumbnailsselection[id]){
                    cb.setChecked(false);
                    thumbnailsselection[id] = false;
                } else {
                    cb.setChecked(true);
                    thumbnailsselection[id] = true;
                    selectedImage();

                }
            }
        });
        holder.imageview.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                int id = v.getId();
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse("file://" + arrPath[id]), "image/*");
                startActivity(intent);
            }
        });
        holder.imageview.setImageBitmap(thumbnails[position]);
        holder.checkbox.setChecked(thumbnailsselection[position]);
        holder.id = position;

        return convertView;
    }

}
class ViewHolder {
    ImageView imageview;
    CheckBox checkbox;
    int id;
}

}

Gallery_item.xml

<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<ImageView
    android:id="@+id/thumbImage"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:src="@mipmap/ic_launcher"
    android:layout_centerInParent="true" />

<CheckBox
    android:id="@+id/itemCheckBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:buttonTint="@android:color/white"
    android:layout_alignParentRight="true"
    android:layout_alignParentBottom="true" />
    </RelativeLayout>

activity_main.xml

<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="fill_parent"
xmlns:app="http://ift.tt/GEGVYd"
android:background="@android:color/white"
android:layout_height="fill_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_top"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="#F4E178">
    <ImageView
        android:id="@+id/backbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>
    <CheckBox
        android:id="@+id/chkSelectAll"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:buttonTint="@android:color/white"
        app:buttonTint="@android:color/black"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Select All"
        android:textColor="#D7793A"
        android:textSize="20dp"
        android:id="@+id/toolbar_title" />
    <ImageView
        android:id="@+id/btnDelete"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher"/>

</android.support.v7.widget.Toolbar>


<GridView
    android:id="@+id/PhoneImageGrid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:columnWidth="80dp"
    android:gravity="center"
    android:horizontalSpacing="5dp"
    android:numColumns="auto_fit"
    android:stretchMode="columnWidth"
    android:verticalSpacing="5dp" />
<Button
    android:id="@+id/selectBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:minWidth="200px"
    android:text="Select" />
  </LinearLayout>

Log cat

03-31 07:36:03.423 25505-25505/dixit.com.multiselectgallery E/AndroidRuntime: FATAL EXCEPTION: main Process: dixit.com.multiselectgallery, PID: 25505 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setChecked(boolean)' on a null object reference at dixit.com.multiselectgallery.MainActivity$1.onClick(MainActivity.java:90) at android.view.View.performClick(View.java:4780) at android.widget.CompoundButton.performClick(CompoundButton.java:120) at android.view.View$PerformClick.run(View.java:19866) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)




Aucun commentaire:

Enregistrer un commentaire