I want to add a second on click to a ListViewItem.
I already created the View (ImageView) and i set the on Click. The function gets called.
But: How can i get the Informations of this ListViewItem? It would be enough to get the Position in the ListView?
The ImageView:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:onClick="favorite"
android:src="#drawable/star" />
The code for my on click function:
public void favorite(View view){
ImageView iView = (ImageView) view;
iView.setImageResource(R.drawable.star_checked);
ViewParent v = iView.getParent();
}
Use an anonymous inner class:
ImageView iView = (ImageView) findViewById(R.id.imageView1);
iView.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//Your code
}
});
myListView.setOnItemClickListener(new OnItemClickListener() { ![enter image description here][2]
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value = myListView.getAdapter().getItem(position).toString(); // String value of the clicked item
//Code
}
});
If you want to make bigger applications you should think about better naming your components, 'imageView1' is not very handy. Name you components like 'imageview_main' or 'imageview_customerdetails'.
Subclass OnItemClickListener rather than OnClickListener.
Edit:
Okay I think I understand what you are trying to do now. I would subclass your ListAdapter and override the getView(int position, ...) method like so:
private OnClickListener mImgClickListener = new OnClickListener() {
#Override
public void onClick(View view) {
int position = (Integer) view.getTag();
// do stuff with position knowledge!
}
});
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView != null) {
v = convertView;
} else {
v = newView(int position);
}
v.findViewById(R.id.imageView1).setTag(position);
return v;
}
private View newView(int position) {
View v;
// inflate your view here
View imageView = v.findViewById(R.id.imageView1);
imageView.setOnClickListener(mImgClickListener);
return v;
}
Of course, even better would be to implement the ViewHolder pattern in the getView method to eliminate expensive calls to findViewById.
I believe the View hierarchy will take care of giving priority to the click on the ImageView (rather than the list item as a whole), but I could be wrong.
Related
listContent.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for(int i=0;i<showLists.size();i++){
//
TextView v=(TextView)listContent.getChildAt(i).findViewById(R.id.txtDes);
v.setTextColor(Color.BLACK);
}
TextView v=(TextView)listContent.getChildAt(position).findViewById(R.id.txtDes);
v.setTextColor(Color.RED);
Toast.makeText(context,"POS "+showLists.get(position).getDes(),Toast.LENGTH_SHORT).show();
}
});
I have been the problem with get position item of listview. Android just has shown about 12 row on devide's creen, when I click another item on listview (my listview have 30 item ) which shown the error.
And this is error:
"Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference" .
Thanks for read.
listContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for (int i = 0; i < showLists.size(); i++) {
TextView v = (TextView) view.findViewById(R.id.txtDes);
v.setTextColor(Color.BLACK);
}
TextView v = (TextView) view.findViewById(R.id.txtDes);
v.setTextColor(Color.RED);
Toast.makeText(context, "POS " + showLists.get(position).getDes(), Toast.LENGTH_SHORT).show();
}
});
Your question is indeed about Null Pointer Exception, but is harder to identify why this is happening. The problem can be found here:
for(int i=0;i<showLists.size();i++){ <-- this line actually causes the crash
//
the crash is in the next line, at the findViewById
TextView v=(TextView)listContent.getChildAt(i).findViewById(R.id.txtDes);
v.setTextColor(Color.BLACK);
}
Your for has the wrong upper limit because of a mechanism known as recycling, and because of this mechanism your list view will never have the same number of rows as the amount of data that needs to be displayed (read about recycling to understand this). Given this fact, we know for sure that the number of views found in list view (listContent.getChildCount()) will be smaller than showLists.size() and thus making the call listContent.getChildAt(i) to return a NULL value when the index equals listContent.getChildCount() creating the crash.
Now you might be tempted to change showLists.size() with listContent.getChildCount() and see that the app doesn't crash anymore, but if you click a row, then other rows are coloured also as you scroll the list (the recycling is again the problem). To really fix the problem you should save the index of the selected row and call notifyDatasetChanged, so when getView is called in adapter you simply check the current position to be displayed with the selected position. In case of equality you change the color of text to red, otherwise to black. Below, you will find some parts of an example:
int currentPosition = -1;
// Just a basic adapter. The getView method is the key here
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1) {
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View view = super.getView(position, convertView, parent);
if (position == currentPosition) {
((TextView) view).setTextColor(Color.RED);
} else {
((TextView) view).setTextColor(Color.BLACK);
}
return view;
}
};
// and here is the onItemClick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentPosition = position;
adapter.notifyDataSetChanged();
}
});
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewRow=convertView;
if(viewRow==null){
viewRow=inflater.inflate(layout,parent,false);
viewHolder viewHolder=new viewHolder();
viewHolder.imgIcon = (ImageView) viewRow.findViewById(R.id.imgIcon);
viewHolder.txtDes = (TextView) viewRow.findViewById(R.id.txtDes);
viewRow.setTag(viewHolder);
}
viewHolder holder= (viewHolder) viewRow.getTag();
holder.imgIcon.setImageResource(listMoiNhat.get(position).getIcon());
holder.txtDes.setText(listMoiNhat.get(position).getDes());
if(position==currentpos){
holder.txtDes.setTextColor(Color.RED);
}
else {
holder.txtDes.setTextColor(Color.RED);
}
return viewRow;
}
//and here is create customListMoiNhat object
final customListMoiNhat customListMoiNhat=new customListMoiNhat(context,R.layout.moinhat_customlistview,showLists,currentpos);
customListMoiNhat.notifyDataSetChanged();
listContent.setAdapter(customListMoiNhat);
listContent.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
currentpos=position;
customListMoiNhat.notifyDataSetChanged();
}
});
I created a custom listview layout with images which are loaded from web like this:
http://i.stack.imgur.com/l8ZOc.png
It works fine when scrolling down. However, when you scroll down, the previous items go out of screen then destroyed. When you try to scroll up again, it gets loaded again (from cache, faster but not instant) which causes a delay and it is not fluent as it should be.
1.Is there an example of how to do this properly?
2.Is there a way to prevent listview items being destroyed when they are out of screen?
3.If so, will it cause problems to keep too many items?
Bellow is my code:
MenuAdapter:
public class MenuAdapter extends BaseAdapter{
Context context;
List<MyMenuItem> menuItems;
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.context = context;
this.menuItems = menuItems;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return menuItems.get(position);
}
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
private class ViewHolder {
ImageView ivMenu;
TextView tvMenuHeader;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_item, null);
holder = new ViewHolder();
holder.tvMenuHeader = (TextView) convertView.findViewById(R.id.tvMenuHeader);
holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenuItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyMenuItem row_pos = menuItems.get(position);
Picasso.with(context)
.load(row_pos.getItem_image_url())
.into(holder.ivMenu);
holder.tvMenuHeader.setText(row_pos.getItem_header());
Log.e("Test", "headers:" + row_pos.getItem_header());
return convertView;
}
}
MyMenuItem:
public class MyMenuItem {
private String item_header;
private String item_image_url;
public MyMenuItem(String item_header, String item_image_url){
this.item_header=item_header;
this.item_image_url=item_image_url;
}
public String getItem_header(){
return item_header;
}
public void setItem_header(String item_header){
this.item_header=item_header;
}
public String getItem_image_url(){
return item_image_url;
}
public void setItem_image_url(String item_image_url){
this.item_image_url=item_image_url;
}
}
MainActivity:
public class MyActivity extends Activity implements AdapterView.OnItemClickListener {
List<MyMenuItem> menuItems;
ListView myListView;
JSONArray jsonArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Bundle extras = getIntent().getExtras();
if(extras!=null){
try{
jsonArray = new JSONArray(extras.getString("Data"));
}catch (Exception e){
e.printStackTrace();
}
}
menuItems = new ArrayList<MyMenuItem>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
MyMenuItem item = new MyMenuItem(jsonArray.getJSONObject(i).getString("title"), jsonArray.getJSONObject(i).getString("imageURL"));
menuItems.add(item);
}catch (Exception e){
e.printStackTrace();
}
}
myListView = (ListView) findViewById(R.id.list);
MenuAdapter adapter = new MenuAdapter(this, menuItems);
myListView.setAdapter(adapter);
myListView.setOnItemClickListener(this);
}
}
MenuItem.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/ivMenuItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="center"
android:src="#drawable/em" />
<TextView
android:id="#+id/tvMenuHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#55000000"
android:paddingBottom="15dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="15dp"
android:textColor="#android:color/white"
android:layout_gravity="left|top"
android:layout_alignBottom="#+id/ivMenuItem"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
1. Is there an example of how to do this properly?
Your code looks pretty close to perfect. The Adapter's getView method is usually the critical path to optimize. Compare for example Picasso's own example SampleListDetailAdapter.java. The important points it (as well as your code) does
check for & re-use already inflated views, inflation is expensive.
use ViewHolder so you don't have to call findViewById every time. Not terribly expensive on simple views. Also cached afaik.
Picasso.with(context).load(url)... each time you need to display an image. This should finish instantly but still use caches and other magic.
There are some minor optimizations you can add, but I doubt that there are noticeable or even measurable changes:
pure style change: use BaseAdapter#getItem(position). This method
exists for you only. The framework doesn't use it.
#Override
public MyMenuItem getItem(int position) { // << subclasses can use subtypes in overridden methods!
return menuItems.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
MyMenuItem row_pos = getItem(position);
Use a sane id method
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
is equivalent to
#Override
public long getItemId(int position) {
return position;
}
but now infinitely faster. indexOf(Object) scales really badly with the number of objects.
Cache objects that don't change:
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.mLayoutInflater = LayoutInflater.from(content);
this.mPicasso = Picasso.with(context);
}
..
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_item, null);
...
mPicasso
.load(row_pos.getItem_image_url())
.into(holder.ivMenu);
2. Is there a way to prevent listview items being destroyed when they are out of screen?
No(*).
..(*) well you can essentially cache the result of getView e.g. in LruCache(position, View) or LruCache(MyMenuItem, View), then don't touch the convertView - they need to remain unconverted or you would kill those views in your cache. Also
#Override
public int getItemViewType(int position) {
return Adapter.IGNORE_ITEM_VIEW_TYPE;
}
seemed to be required because the standard adapter using code assumes that views it removes from visibility are gone. They are not and messing with them messes with your cache and caused weird display problems for me.
3. If so, will it cause problems to keep too many items?
Yes. This behavior is not intendend / expected. There is also more or less nothing you gain. You might be able to save you the call to holder.tvMenuHeader.setText(). Likewise the one to Picasso but both of them should complete instantly. Picasso should have your image cached already. By caching all Views you essentially add another cache that also contains all the images. I would rather check that the picasso cache works as intended and holds most items. The only reason you may want to do it with view caching is for cases that require complicated setup of the view, so it becomes worth caching the completely constructed view rather than just some content parts.
Profile
Profiling can actually tell you where you can / need / should improve. The first to look at IMO is traceview. You'll see if code blocks the main thread which results in choppy list scrolling. If you're doing complicated views and you see that the draw methods are executed most of the time, profile them as well.
http://www.curious-creature.org/docs/android-performance-case-study-1.html
http://blog.venmo.com/hf2t3h4x98p5e13z82pl8j66ngcmry/performance-tuning-on-android
http://www.vogella.com/tutorials/AndroidTools/article.html
I have search on StackOverflow and other websites but no one can answer to my question.
I have a gridView with items. I have a button to add item to this gridView.Each element on the GridView is a relativeLayout with an Imageview and an EditText.
When i add item to the gridView using the button, I want to get my relativeLayout and request Focus on the editText to set a name on it.
Imagine i have 3 elements in my gridView.
I add element to my ArrayList and call adapter.notifiyDataSetChanged().
The new element is displayed on the grid but when i use getChildCount(), the gridView still has 3 children.
It cause problem because i want to request focus on the last added EditText.
How can i update my gridView object ?
Fragment :
//Get gridView
final GridView gridCat = (GridView) v.findViewById(R.id.gridCategory);
adapter = new GridCategoryAdapter(getActivity(), subcatList);
gridCat.setAdapter(adapter);
gridCat.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SubCategory subcat = subcatList.get(position);
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.fragment_middle, SubCategoryFragment.newInstance(subcat.getProducts(), subcat.getName()));
transaction.addToBackStack(null);
transaction.commit();
}
});
Button catAddButton = (Button) v.findViewById(R.id.catAddButton);
catAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "old size gridview : " + gridCat.getChildCount());
subcatList.add(new SubCategory());
Log.d(TAG, "new size list : " + subcatList.size());
adapter.notifyDataSetChanged();
Log.d(TAG, "new size gridview : " + gridCat.getChildCount());
//HERE : childCount is the same !
RelativeLayout rl = (RelativeLayout) gridCat.getChildAt(gridCat.getChildCount()-1);
rl.findViewById(R.id.subcatName).setFocusable(true);
rl.findViewById(R.id.subcatName).setLongClickable(true);
rl.findViewById(R.id.subcatName).requestFocus();
}
});
My Adapter :
public class GridCategoryAdapter extends BaseAdapter {
private static final String TAG = "com.zester.manager.ListViewSizeAndPriceAdapter";
private LayoutInflater mInflater;
private final Context context;
private ArrayList<SubCategory> listSubCat;
private ViewHolder holder;
public GridCategoryAdapter(Context context, ArrayList<SubCategory> values) {
super();
this.context = context;
listSubCat = values;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listSubCat.size();
}
#Override
public Object getItem(int position) {
return listSubCat.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.subcat_view, null);
holder = new ViewHolder();
holder.SubCatName = (EditText) convertView.findViewById(R.id.subcatName);
holder.imageSubCat = (ImageView) convertView.findViewById(R.id.imageSubCatView);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
SubCategory subCat = (SubCategory) getItem(position);
if (subCat != null) {
holder.SubCatName.setText(subCat.getName());
holder.imageSubCat.setImageDrawable(context.getResources().getDrawable(R.drawable.subcat_default));
}
return convertView;
}
static class ViewHolder {
public EditText SubCatName;
public ImageView imageSubCat;
}
}
XML for each item on the gridview :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/imageSubCatView"
android:src="#drawable/subcat_default"
android:layout_centerHorizontal="true"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/subcatName"
android:gravity="center_horizontal"
android:hint="Ex : Bières"
android:layout_marginTop="20dp"
android:layout_below="#+id/imageSubCatView"
android:background="#android:color/transparent"
android:singleLine="true"
android:focusable="false"
android:longClickable="false"/>
Thx a lot !
When i tried to get my RelativeLayout, null is return : RelativeLayout rl = (RelativeLayout) gridCat.getChildAt(gridCat.getCount()-1);
I think your answer is this:
when you add
subcatList.add(new SubCategory());
adapter.notifyDataSetChanged();
to your code it is not guaranteed that new view for them has been created, because it is possible that your gridView has 100 children and you are just looking at children from 7 to 20 , so new child at index 100 has not yet inflated because the getView is called upon request in order to save memory so when there is no need to show the 100th child, why it must be called? so relativelayout for that child is null because it has not inflated.
in catAddButton listener you must not touch any gridview item, because when the button click happens it first runs your listener then scrolls to the end of gridView so still you have problem, what sholud you do?
in class of SubCategory() put variable that indicates it has not shown for the first time. in getView of gridview each time you want to inflate new items look at that variable (in the list of your SubCategory at item list.get(position)) and for example if it is boolean toggle it to false so that means the new object is going to be seen by user. So in this way each time you are going to inflate the view you know that if it is the first time or not, if it is first time your boolean is true else it has already been false. if it is not first time remove focus else put focus by calling reqesFocuse.
I am showing a List in a ListView through a custom adapter SongsListAdapter.java with custom itemview music_item.xml and there is a method i want to call in my Activity Class MainActivity.java so i cannot use setOnClickListener method
what i did is i added an attribute to music_item.xml onClickto call method in MainActivity.java
but this is not working, by clicking the list item it is not invoking the method from Activity class
SongsListAdapter.java
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.music_item, null);
this.mView = view;
holder.title = (TextView) view.findViewById(R.id.songName);
holder.descr = (TextView) view.findViewById(R.id.songArtists);
holder.dp = (ImageView) view.findViewById(R.id.albumIcon);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(SongsListItemslist.get(position).getDisplayName());
holder.descr.setText(SongsListItemslist.get(position).getArtist());
holder.dp.setImageBitmap(SongsListItemslist.get(position).getBitmap());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
return view;
}
MainActivity.java
public void songPicked(View view) {
Log.v("clicked", "clicked");
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
}
Music_item.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/card"
android:clickable="true"
android:onClick="songPicked" >
<ImageView
android:id="#+id/albumIcon"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/abc_ab_bottom_solid_dark_holo" />
</RelativeLayout>
And i couldn't able to see clicked in my Logs..
Delete this from your SongsListAdapter.java
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
you are setting a onClick Listener with an empty action in your adapter that isn´t necessary, use only the method defined in your Layout:
android:onClick="songPicked"
You don't want to set a listener on the Layout of your list item Music_item. This will be covered under the setOnItemClickListener of your ListView.
see: setOnItemClickListener on custom ListView
Firstly you have to remove
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
}
});
and then if you want ot handle the click on the ListView you need to call this from the MainActivity
list.setAdapter(yourCustomAdapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.v("clicked", "clicked");
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
}
});
Don't forget to remove onClick attribute from the RelativLayout.
Good luck..
You say you cannot use setOnClickListener, I'm not sure why? In your adapter constructor, you can pass in the Activity, set it as a variable in your adapter class and use it in your on click listener to call a method defined in Activity.
Alternatively, use setOnItemClickListener in your activity or fragment (ie where you initially set the adapter).
I have a GridView with custom View in it, which is a Button and a TextView. I defined the setOnItemClickListener but it looks like it never invoked, please see peaces of code below.
gridview = (GridView) findViewById(R.id.main_gridview);
gridview.setAdapter(new GridAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), "gadsfadsf",
Toast.LENGTH_SHORT).show();
Log.d("Main", "onItemClick");
}
});
The marked answer is kind of a hack. Instead of setting an onclicklistener to the button just ensure, that the ButtonView and the TextView has the following property:
android:clickable="false"
I had the same issue. While I've not yet figured out why it never gets invoked, I can propose a workaround.
Instead of setting the onClickListener on your GridView, set it on the Button itself inside your GridAdapter, inside your getView() method.
That worked for me!
It could be that some items in your GridView are stealing focus. Try adding these attributes to any elements you have inside the grid:
android:focusable="false"
android:focusableInTouchMode="false"
Instead of setting the onClickListener on your GridView,
set it on the Button itself inside your GridAdapter, inside your getView() method.
That worked for me!
I had the same problem, the event grid.itemClickListener was never launched.
In my case I had two listeners: grid.itemClickListener and another clickListener attached to a Button within the item's layout.
After fiddling with the layout for a while, I realized that if there was a widget, within the item's layout, with focusable=true, then itemClickListener was never launched. The clickListener attached to the Button worked well though.
Maybe that was your case. Anyway, I think this information might be useful to other users running into the same problem.
Thanx to CodingUser
what we were doing is directly accessing the Layout inside the GridView, so the onItemClickListener finds it confusing to access the item.
So the solution is to apply the onClickListener inside the Adapter (i.e. normally ArrayAdapter)
so what i m trying to say is:
public View getView(int position, View convertView, ViewGroup parent) {
//Here row is a view and we can set OnClickListener on this
final View row;
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
//Here we inflate the layout to view (linear in my case)
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
row = convertView;
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
//Now get the id or whatever needed
row.setId(position);
// Now set the onClickListener
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "Clicked" + row.getId() + "!!",
Toast.LENGTH_SHORT).show();
}
});
return row;
}
You can set OnClick for view in Adapter of GridView .It work for me .
public View getView(final int position, View convertView, ViewGroup parent) {
ObjMenuVideo objListVideo = mListMenuVideo.get(position);
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_video_of_kind, null);
holder.tv_number_views = (TextView) convertView
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv_number_views.setText(String.valueOf(objListVideo.getViews()));
convertView.setId(position);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent menuVideoIntent = new Intent(mContext,
ActivityDetailVideo.class);
mContext.startActivity(menuVideoIntent);
}
});
return convertView;
}