GridView.setOnItemClickListener triggers whole row - java

I have a grid view 3x3. Inside this grid I have ImageViews.
I set up OnItemClickListener but when I click on the ImageView only the first one is pressed in a row no matter which column I am pressing. Also I can be pressing outside the ImageView (empty space) but still first ImageView on that row is pressed.
XML
<GridView
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
MainActivity
GridView gridview = (GridView) findViewById(R.id.test);
gridview.setAdapter(new HexAdapter(getBaseContext()));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Log.e("gridView", "hallo" + position);
}
});
and this is my adapter
public class HexAdapter extends BaseAdapter {
private Context mContext;
public HexAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return (Object) mThumbIds[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo,
R.drawable.logo, R.drawable.logo,
};
}
R.drawable.logo is just a random image a chose.

I have experienced this problem and the solution I came up with is simple:
In your adapter give an unique TAG to each view
view.setTag(id); //example
And on ItemClickListener just match the tags for each view and you will be sure this will never happen:
if(view.getTag().equals(id))
doStuff();
if(view.getTag().equals(otherId))
doOtherStuff();
And so on.
Here is an example:
Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ImageView imageView;
CustomTextView textView;
LinearLayout main_grl;
if (v == null) {
v = layoutInflater.inflate(R.layout.professions_gridview_item,parent,false);
}
main_grl = (LinearLayout)v.findViewById(R.id.main_grl);
main_grl.setBackground(ContextCompat.getDrawable(mContext,R.drawable.ps_background_selector));
imageView = (ImageView) v.findViewById(R.id.imageView);
textView = (CustomTextView) v.findViewById(R.id.textView);
imageView.setImageResource(ApplicationConstants.finalListIV[position]);
textView.setText(ApplicationConstants.finalListTV[position]);
v.setTag(ApplicationConstants.finalListTV[position]);
return v;
}
Activity
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if((Integer) view.getTag() == someTag){
//doStuff
} else if((Integer) view.getTag() == otherTag){
//doOtherStuff
} else{
//andSomeOther
}
}

Related

ImageAdapter cannot be applied to fragment class

I've followed the documentation on how to use GridView and had the same issue as this guy ImageAdapter cannot be applied to a Fragment Class
The code in my Fragment Class is as follows
public class SecondFragment extends Fragment {
View myView;
GridView gridview;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.second_layout, container, false);
gridview = (GridView) myView.findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(getActivity()));
return myView;
}
}
However I'm getting an error in the second to last line "Image Adapter cannot be applied to android.app.activity"
My ImageAdapter is as follows
public class ImageAdapter extends BaseAdapter {
private Context mcontext;
#Override
public int getCount() {
return mthumbids.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mcontext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else {
imageView = (ImageView)convertView;
}
return imageView;
}
private Integer[] mthumbids =
{
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6
};
}
You need to have a constructor in your ImageAdapter class which will take the context as a parameter.
And you have to set the background of the image based on the adapter position as well.
Here's the modified adapter class.
public class ImageAdapter extends BaseAdapter {
private Context mcontext;
public ImageAdapter (Context context) {
mContext = context;
}
#Override
public int getCount() {
return mthumbids.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mcontext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
// Add the following to load the image
imageView.setBackground(ContextCompat.getDrawable(context, mthumbids[position]));
}
else {
imageView = (ImageView)convertView;
}
return imageView;
}
private Integer[] mthumbids =
{
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6
};
}
You can also get the context from the parent in getView(). Then you don't have to pass and store the context. So your getView looks like this:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
Context context = parent.getContext(); // <-- add this line
imageView = new ImageView(context); // use the context from the parent
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
else {
imageView = (ImageView)convertView;
}
return imageView;
}
Missing constructor with argument context for ImageAdapter.
Only empty constructor will be created automatically
you should write constructors with specific argument values.
public ImageAdapter(Context context){
mContext = context;
}
Add this code in ImageAdapter class.
public ImageAdapter (Context context) {
super();
mContext = context;
}

How to display the actual image onclick from gridview

I'm trying to get the image in the chat box when I click on any of the images from the gridview however, whenever I try to do so it comes up with a text, so please advise what can be done to get the image itself instead of the text that is appearing, please help me out I've been stuck for too long
smiles_items_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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/smile_image_view"
android:layout_width="45dp"
android:layout_height="45dp"
android:layout_gravity="center"/>
</LinearLayout>
BottomSheetDialog_Smiles.java
public class ImageAdapter2 extends BaseAdapter {
private Context mContext;
private final int[] mThumbIds;
String[] mThumbIdsString = null;
public ImageAdapter2(Context c, int[] mThumbIds , String[] mThumbIdsString)
{
mContext = c;
this.mThumbIds = mThumbIds;
this.mThumbIdsString = mThumbIdsString;
}
#Override
public int getCount() {
return mThumbIds.length & mThumbIdsString.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
ImageView img;
}
#Override
public View getView(final int position, final View convertView,
ViewGroup parent) {
final Holder holder = new Holder();
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
grid = inflater.inflate(R.layout.smiles_items_layout, null);
null);
holder.img = (ImageView) grid.findViewById(R.id.smile_image_view);
holder.img.setImageResource(mThumbIds[position]);
gridView2.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
Drawable drawable;
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int i, long l) {
JSONDictionary imageChat = new JSONDictionary();
LinearLayout layout= (LinearLayout)view;
ImageView imageView = (ImageView) layout.getChildAt(0);
imageView.getDrawable();
imageChat.put("message", imageView);
Communicator.getInstance().emit("new chat message",
imageChat);
}
});
return grid;
}
}
This is the result which appears when clicking on the image
Do you need an ImageView inside an image?
I used this code to get an image.
Send your view this method get as image.
protected Bitmap ConvertToBitmap(ImageView image_view) {
Bitmap map;
image_view.setDrawingCacheEnabled(true);
image_view.buildDrawingCache();
return map=image_view.getDrawingCache();
}
In ur adapter code
holder.img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bitmap b = ConvertToBitmap(holder.img);;
//now get bitmap used to assign
imageChat.put("message", b);
Communicator.getInstance().emit("new chat message",
imageChat);
}
});

Converting an Integer to a Drawable

I have two Adapter classes and in the first one, i have an Array of Integers[] named mThumbIds which is initialized like this :
// References to our images
private Integer[] mThumbIds = {
R.mipmap.beyondthe_ferocious_flash_majin_vegeta_icon,
R.mipmap.full_tilt_kamehameha_super_saiyan2_gohan_youth_icon,
R.mipmap.merciless_condemnation_goku_black_super_saiyan_rose_and_zamasu_icon,
R.mipmap.everlasting_legend_super_saiyan_goku_icon,
R.mipmap.indestructible_saiyan_evil_legendary_super_saiyan_broly_icon
};
I want to extract an Integer from this array(let's say mThumbIds[0]) and then pass it into my other adapter class and use it to get a valid drawable that i can use for my imageViews.
This is the 2nd adapter's List to hold the extracted Integer:
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
And here is where i need the drawable :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mGLBIcons.get(position));
return imageView;
}
So far, nothing that i've tried has worked so i am asking for your help!
EDITED
ImageViewAdapterClass:
public class UserBoxGlbImageAdapter extends BaseAdapter {
Context mContext;
public UserBoxGlbImageAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
return mGLBIcons.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
// Used to add card icons from the mainScreenFragment
public List<Integer> getGLBIconsList() {
return mGLBIcons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
// If it's not recycled, initialize some attributes
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Drawable drbl = mContext.getResources().getDrawable(mGLBIcons.get(0));
imageView.setImageDrawable(drbl);
return imageView;
}
public void passInteger(Integer integer) {
mGLBIcons.add(integer);
}
}
GridSettingFragmentClass:
public class UserBoxGLBFragment extends Fragment {
GridView globalGridView;
public UserBoxGLBFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
globalGridView = view.findViewById(R.id.userBoxGlbGridView);
globalGridView.setAdapter(new UserBoxGlbImageAdapter(getContext()));
return view;
}
}
fragment_user_box_glb.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorSecondaryGLB"
android:orientation="vertical"
tools:context="com.dcv.spdesigns.dokkancards.ui.UserBoxGLBFragment">
<GridView
android:id="#+id/userBoxGlbGridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="4"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
</LinearLayout>
you are using mipmap id and you are trying to load it as a drawable, i doubt it will work. try putting the images in the drawable folder and use thr drawable id.
this is how you set a drawable image in a adapter:
imageView.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_success))
in your case it would be
imageView.setImageDrawable(context.getResources().getDrawable(listOfImages[position]))
Change your constructoras:
public UserBoxGlbImageAdapter(Context c, List<Integer> iconsList) {
mContext = c;
mGLBIcons = iconsList;
}
try using as below:
image_view_layout xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/image_view"
android:layout_width="225dp"
android:layout_height="225dp" />
</LinearLayout>
public class UserBoxGLBFragment extends Fragment {
GridView globalGridView;
List<Integer> listOfimages = new ArrayList<>();
public UserBoxGLBFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_box_glb, container, false);
listOfimages.add(R.drawable.beyondthe_ferocious_flash_majin_vegeta_icon);
globalGridView = view.findViewById(R.id.userBoxGlbGridView);
globalGridView.setAdapter(new UserBoxGlbImageAdapter(getContext(),listOfimages));
return view;
}
}
public class UserBoxGlbImageAdapter extends BaseAdapter {
Context mContext;
// References to the images via a List
private List<Integer> mGLBIcons = new ArrayList<>();
public UserBoxGlbImageAdapter(Context c,List<Integer> listOfIcons) {
mContext = c;
mGLBIcons = listOfIcons;
}
#Override
public int getCount() {
return mGLBIcons.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
// Used to add card icons from the mainScreenFragment
public List<Integer> getGLBIconsList() {
return mGLBIcons;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If it's not recycled, initialize some attributes
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_view_layout, parent, false));
}
ImageView imageView = (ImageView)convertView.findViewById(R.id.image_view)
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8); imageView.setImageDrawable(mContext.getResources().getDrawable(mGLBIcons.get(0)));
return imageView;
}
}

Android Studio Dynamically Changing Images in GridView

I have set up a GridView Successfully, however I want to be able to change the Images within the the GridView dependent upon a variable. For example:
int a = 2
if (a == 2){
Integer[] images = {
R.drawable.image1
R.drawable.image3
}
} else {
Integer[] images = (
R.drawable.image2
R.drawable.image4
}
}
However I can't find a way to do this. The code I am working with at the moment is:
GridView cardList = (GridView) findViewById(R.id.cardList);
cardList.setAdapter(new ImageAdapter(this));
cardList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(Create.this, "" + position,
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return images.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(215, 215));
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(images[position]);
return imageView;
}
private Integer[] images = {
R.drawable.iamge1, R.drawable.image2
};
}
Try something like this:
The activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.gridView);
int images[] = {R.drawable.ic_action_name};
ImageAdapter imageAdapter = new ImageAdapter(getApplicationContext(),images);
gridView.setAdapter(imageAdapter);
}
}
Your adapter class:
public class ImageAdapter extends BaseAdapter {
private int images[];
Context context;
public ImageAdapter(Context context, int images[]){
this.context = context;
this.images = images;
}
private class Holder{
ImageView imageView;
}
#Override
public int getCount(){
return images.length;
}
#Override public Object getItem(int position){
return null;
}
#Override
public long getItemId(int position){
return 0;
}
#Override
public View getView(final int position, View view, ViewGroup parent){
//All of this Holder stuff is so that the View doesn't jump around wildly
final Holder holder;
LayoutInflater inflater;
if (view == null){
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.singleimage,null);
holder = new Holder();
holder.imageView = (ImageView) view.findViewById(R.id.singleImage);
view.setTag(holder);
}
else {
holder = (Holder) view.getTag();}
holder.imageView.setImageResource(images[position]);
return view;
}
}
You also need a simple xml file for the single image in the gridView. Name this "singleimage.xml"
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/singleImage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
Activity xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ri.emily.testapp.MainActivity">
<GridView
android:layout_width="match_parent"
android:id="#+id/gridView"
android:layout_height="match_parent" />
</RelativeLayout>

Checked Item in GridView

I want to check every item which I click in GridView , after I keep hold on a picture and start onItemCheckedStateChanged.. I mean I want to change programatically every background of the each image I would check, and I don't know how...
Here is my GridViewAdapter :
public class GridViewAdapter extends BaseAdapter {
// Declare variables
ImageView image;
private Activity activity;
private String[] filepath;
private String[] filename;
private static LayoutInflater inflater = null;
public GridViewAdapter(Activity a, String[] fpath, String[] fname) {
activity = a;
filepath = fpath;
filename = fname;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return filepath.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.gridview_item, null);
// Locate the TextView in gridview_item.xml
TextView text = (TextView) vi.findViewById(R.id.text);
// Locate the ImageView in gridview_item.xml
image = (ImageView) vi.findViewById(R.id.grid_image);
// Set file name to the TextView followed by the position
File file = new File(filepath[position]);
Picasso.with(activity).load(file).placeholder(R.drawable.rtrt).fit().centerCrop().into(image);
// Decode the filepath with BitmapFactory followed by the position
// Set the decoded bitmap into ImageView
// image.setImageBitmap(bmp);
return vi;
}
}
And here is the main activity onItemCheckedStateChanged :
public class MultiChoiceModeListener implements
GridView.MultiChoiceModeListener {
#Override
public void onItemCheckedStateChanged(android.view.ActionMode mode, int position, long id, boolean checked) {
selectCount = grid.getCheckedItemCount();
int checkedItemPosition = grid.getCheckedItemPosition();
switch (selectCount) {
case 1:
mode.setSubtitle("One picture selected");
break;
default:
mode.setSubtitle("" + selectCount + " pictures selected");
break;
}
}
#Override
public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
mode.setTitle("Select pictures");
mode.setSubtitle("One picture selected");
return true;
}
#Override
public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
return true;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
return true;
}
#Override
public void onDestroyActionMode(android.view.ActionMode mode) {
}
}
I'm stucked for 2 days on this issue , any help will be apreciated!!! Thanks!
Make sure for each ImageView or TextView you want to replace with different parameters you need to have their
replacement set visibility for “invisible”, so when you click on Item it would change for “visible”.
XML objects would look like this:
<ImageView
android:id="#+id/grid_image"/>
<ImageView
android:id="#+id/check_grid_image"
android:visibility="invisible"/>
GridViewAdapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.inflate(R.layout.gridview_item, null);
holder = new ViewHolder();
holder.image = (ImageView)convertView.findViewById(R.id.grid_image);
holder.checkImage = (ImageView)convertView.findViewById(R.id.check_grid_image);
convertView.setTag(holder);
}
GridView gridView = (GridView)parent;
if (gridView.isItemChecked(position)) {
holder.checkImage.setVisibility(View.VISIBLE);
}
else {
holder.checkImage.setVisibility(View.INVISIBLE);
}
// Picasso omitted
return convertView;
}
private static class ViewHolder {
ImageView image;
ImageView checkImage;
}
ActivityMain:
protected AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageView checkImage = (ImageView)view.findViewById(R.id.check_grid_image
if (mGridView.isItemChecked(position)) {
// Action when Item checked
checkImage.setVisibility(View.VISIBLE);
}
else {
// Reverse Action
checkImage.setVisibility(View.INVISIBLE);
}
}
};
This is working in my project, but let me know if that works for you too!

Categories

Resources