I am struggling with trying to implement an OnLongClick feature - I can't understand where to add a listener and to define the resulting method.
The implementation i have used uses an adapter - and does not have an onClickListener, but works jsut fine. can anyone suggest where/how to implement OnLongClick listener
I don't need every item in the list to perform different actions - just for anywere on the screen to pick up the long press
public class CombChange extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ListEdit(this, symbols));
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
if (lastPressed.equals(selectedValue) ){
count++;}
}
public class ListEdit extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ListEdit(Context context, String[] values) {
super(context, R.layout.activity_comb_change, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_comb_change, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values[position]);
// Change icon based on name
String s = values[position];
if (s.equals("a")) {
imageView.setImageResource(R.drawable.a);
return rowView;
}
}
Try this:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
v.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
String selectedValue = (String) getListAdapter().getItem(position);
if (lastPressed.equals(selectedValue) ){
count++;}
return false;
}
});
}
It is unfortunate that a ListActivity does not have a protected onListItemLongClick() method similar to the onListItemClick() function.
Instead, you can add setOnLongClickListener() to the top-level layout item (or any View) in your adapter's getView() function.
Example:
myView.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// Do something here.
return true;
}
});
Warning, the OnLongClickListener you put onto your list item may hide exposure to the onListItemClick() function you already have working for the list. If this is the case, you will also have to add setOnClickListener() to getView() and use it instead.
in your getView you can say
rowview.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View arg0) {
//Do your stuff here
return false;
}
});
Related
I want to use admob with recyclerview but there is a problem. I need to hide some elements that are belong to viewholder. I need to hide the imageview in which position the ImageView belongs. When i click holder.btnReklamIzle the picture in that position must be hid in onRewardedVideoAdLoaded method. How can i transmit the position to onRewardedVideoAdLoaded method?
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_kuponlar, container, false);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(KuponlarFragment.this.getActivity());
mRewardedVideoAd.setRewardedVideoAdListener(this);
tahminlerRecyclerView = root.findViewById(R.id.tahminlerRecyclerView);
linearLayoutManager = new LinearLayoutManager(this.getActivity());
tahminlerRecyclerView.setLayoutManager(linearLayoutManager);
tahminlerRecyclerView.setHasFixedSize(true);
loadRewardedVideoAd();
fetch();
return root;
}
private void loadRewardedVideoAd() {
mRewardedVideoAd.loadAd(getString(R.string.admob_ads_id),
new AdRequest.Builder().build());
}
private void fetch() {
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("tahminler");
FirebaseRecyclerOptions<Mac> options =
new FirebaseRecyclerOptions.Builder<Mac>()
.setQuery(query, new SnapshotParser<Mac>() {
#NonNull
#Override
public Mac parseSnapshot(#NonNull DataSnapshot snapshot) {
return new Mac((double)snapshot.child("oran").getValue(),
snapshot.child("tahmin").getValue().toString(),
);
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Mac, ViewHolder>(options) {
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tahmin_tasarim_recyclerview, parent, false);
return new ViewHolder(view);
}
#Override
protected void onBindViewHolder(final ViewHolder holder, final int position, Mac mac) {
holder.btnReklamIzle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}});
}
};
tahminlerRecyclerView.setAdapter(adapter);
}
#Override
public void onRewardedVideoAdLoaded() {
}
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
}
}
onRewardedVideoAdLoaded is a callback method for an asynchronous operation hence you cannot pass values to it as arguments but use referenced variables.
For your case do the following:
Firstly
Create a global variable to hold the list of views to hide
ArrayList<View> views_to_hide = new ArrayList<>();
Secondly
Create a helper function to hide the views
function hideViews(ArrayList<View> views){
for(View v : views) v.setVisibility(View.GONE);
}
Thirdly
Inside onBindViewHolder Add to the list the views you want to hide under your button onClick
public void onClick(View v) {
//...
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
// Ads already shown you may want to manually hide other images here
}else{
// We only need to add to list when ads not loaded
// We also want to make sure we don't add same view to the list twice
if(!views_to_hide.contains(holder.image))
views_to_hide.add(holder.image);
}});
//...
Finally
Call your helper function inside onRewardedVideoAdLoaded
#Override
public void onRewardedVideoAdLoaded() {
//This hides the views that was added to the list before now
hideViews(views_to_hide);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have an activity that has container that contain fragments and this fragment has other fragments.
Now I want this second or child fragment to access views in main activity, but it returns null pointer exception.
class:
public class ImageListFragment extends AbsListViewBaseFragment implements ObservableScrollViewCallbacks {
public static final int INDEX = 0;
android.support.design.widget.FloatingActionButton mFab;
#Bind(R.id.ic_call)
ImageView mIcCall;
#Bind(R.id.ic_email)
ImageView mIcEmail;
#Bind(R.id.ic_forum)
ImageView mIcForum;
FabToolbar mFabToolbar;
ObservableListView mObservableListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fr_image_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
((ListView) listView).setAdapter(new ImageAdapter(getActivity()));
final SubTaB mainActivity = (SubTaB)getActivity();
ButterKnife.bind(mainActivity);
//////////////// problem here
mFabToolbar = (FabToolbar) rootView.findViewById(R.id.fabtoolbar);
////////////////
getFragmentManager().findFragmentByTag("TAG");
// rootView.findViewById(R.id.fab);
mObservableListView = (ObservableListView)rootView.findViewById(android.R.id.list);
//
mObservableListView.setAdapter(this.listView.getAdapter());
mObservableListView.setScrollViewCallbacks(this);
mainActivity.mFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mainActivity.getApplicationContext(), "msg msg", Toast.LENGTH_LONG).show();
mainActivity.mFabToolbar.expandFab();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImagePagerActivity(position);
}
});
return rootView;
}
#Override
public void onDestroy() {
super.onDestroy();
AnimateFirstDisplayListener.displayedImages.clear();
}
private static class ImageAdapter extends BaseAdapter {
private static final String[] IMAGE_URLS = Constants.IMAGES;
private LayoutInflater inflater;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private DisplayImageOptions options;
ImageAdapter(Context context) {
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub) // تغيير الفيو قبل تحميل الصورة
.showImageForEmptyUri(R.drawable.ic_empty) // لما الصورة فاضية
.showImageOnFail(R.drawable.ic_error) // عند الفشل
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new CircleBitmapDisplayer(Color.WHITE, 5))
.build();
}
#Override
public int getCount() {
return IMAGE_URLS.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.item_list_image, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
ImageLoader.getInstance().displayImage(IMAGE_URLS[position], holder.image, options, animateFirstListener);
return view;
}
}
static class ViewHolder {
TextView text;
ImageView image;
}
#Override
public void onScrollChanged(int i, boolean b, boolean b1) {
}
#Override
public void onDownMotionEvent() {
}
#Override
public void onUpOrCancelMotionEvent(ScrollState scrollState) {
Log.d("","Scroll scroll scroll");
if (scrollState == ScrollState.UP) {
mFabToolbar.slideOutFab();
} else if (scrollState == ScrollState.DOWN) {
mFabToolbar.slideInFab();
}
}
#OnClick(R.id.fab)
void onFabClick() {
mFabToolbar.expandFab();
}
#OnClick(R.id.call)
void onClickCall() {
iconAnim(mIcCall);
}
#OnClick(R.id.ic_email)
void onClickEmail() {
iconAnim(mIcEmail);
}
#OnClick(R.id.ic_forum)
void onClickForum() {
iconAnim(mIcForum);
}
private void iconAnim(View icon) {
Animator iconAnim = ObjectAnimator.ofPropertyValuesHolder(
icon,
PropertyValuesHolder.ofFloat("scaleX", 1f, 1.5f, 1f),
PropertyValuesHolder.ofFloat("scaleY", 1f, 1.5f, 1f));
iconAnim.start();
}
private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {
static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (loadedImage != null) {
ImageView imageView = (ImageView) view;
boolean firstDisplay = !displayedImages.contains(imageUri);
if (firstDisplay) {
FadeInBitmapDisplayer.animate(imageView, 500);
displayedImages.add(imageUri);
}
}
}
}
}
It is not good practise to find and control a view in this way. Views can easily become detached from activities and cause unexpected exceptions.
You should rather look at using callbacks to communicate between fragments and activities if required. That way, it also keeps your code in the correct places - so the activity is the only one touching its own views and the fragment also only touches its own views. It merely tells the activity (via callbacks) that something has happened that the activity might want to know about. It also ensures that the fragments are completely self contained and can be easily reused.
You can read about how to implement callbacks here: http://developer.android.com/training/basics/fragments/communicating.html
Use EventBus to communicate between the activity and the fragment. riggarro suggestion is the correct way. But you can also able to update the base activity views using the EventBus.
For example we need to update a TextView text in a activity from the fragment, follow the steps.
First you need to add the following library as dependency to your project in build.gradle of your app.
compile 'de.greenrobot:eventbus:2.4.0'
First you need to create a Event Object class to communicate between the fragment and activity like below.
public class UpdateTextEvent {
private String sampleTextValue;
public UpdateTextEvent(String textValue) {
this.sampleTextValue = textValue;
}
public String getTextValue() {
return sampleTextValue;
}
}
You need to post a event to the event bus in the fragment to update the TextView in the activity.
public class TestingFragment extends Fragment{
private EventBus bus = EventBus.getDefault()
public TextingFragment(){}
public void onCreate(Bundle onSavedInstanceState){
super.onCreate(onSavedInstanceState);
}
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.sample_activity, parent, false);
...
Button b1 = (Button) v.findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//trigger a update to the activity
bus.post(new UpdateTextEvent("testing"));
}
});
}
}
After that you need to register the bus with the callback of the event in the activity like below.
public class MainActivity extends Activity{
private EventBus bus = EventBus.getDefault();
private TextView textView;
#Override
public void onCreate(Bundle onSavedInstanceState){
super.onCreate(onSavedInstanceState);
....
// The textview going to be updated on posting the event
textView = (TextView) findViewById(R.id.text1);
bus.register(this);
}
public void onEvent(UpdateTextEvent event){
textView.setText(event.getTextValue());
}
}
In this above example the onEvent method will be called when you post a event from the fragment..
Hope it will help you.
I have a RecyclerView that holds a bunch of cards (fetches data from the web, then populates cards). I have the cards forming properly after data is fetched, but now I would now like the set a listener for when each card is clicked. Ideally, after each card is clicked, a new intent will be called with further details about that card's data.
Here is where I initialize the adapter. arrList is an ArrayList that has already been filled from another class
private void initializeAdapter() {
RecycleViewAdapter adapter = new RecycleViewAdapter(arrList);
rv.setAdapter(adapter);
}
This is another class that holds the cards:
public class PersonViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView crimeName,crimeID, crimeAddress, crimeDate, crimeWeapon;
ImageView crimePhoto;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
crimeName = (TextView) itemView.findViewById(R.id.crime_name);
crimeID = (TextView) itemView.findViewById(R.id.crime_id);
crimeAddress = (TextView) itemView.findViewById(R.id.crime_address);
crimeDate = (TextView) itemView.findViewById(R.id.crime_date);
crimeWeapon = (TextView) itemView.findViewById(R.id.crime_weapon);
crimePhoto = (ImageView)itemView.findViewById(R.id.crime_photo);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
// WHAT DO I CALL HERE TO GET THE INDEX OF THE ITEM CLICKED ON ?? //
Log.d("app", "clicked");
}
}
the onClick from above should go to this class (by an intent) and pass the index along with it:
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class CrimeDetails extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_details);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.crime_details, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_crime_details, container, false);
return rootView;
}
}
}
How can I get the Clicked Position of the Card ?
Thanks
Do net set the onClickListener in your onCreateVH method but in onBindViewHolder
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((PersonViewHolder)holder).yourRootLayout.setOnClickListener(getPersonClickListener(position));
}
View.OnClickListener getPersonClickListener(final int position) {
return new View.OnClickListener() {
#Override
public void onClick(View view) {
//TODO whatever you want with position
}
};
}
EDIT:
tyczj is right. Binding the Clicklistener in the onBindViewHolder is a very easy but maybe not the best Solution - however it will work!
Another way is to use the getAdapterPosition() method from Viewholder itself and bind it in the onCreateViewHolder:
#Override
public ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.yourLayoutXml, parent, false);
final ViewHolder holder = new PersonViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = holder.getAdapterPosition();
//check if position exists
if (position != RecyclerView.NO_POSITION) {
//TODO whatever you want
}
}
});
return holder;
}
you use getAdapterPosition() in your ViewHolder
I am doing this slightly different, using a different onClick call, then I can use the
getAdapterPosition()
method to determine which item was clicked.
public static class MyViewHolder extends RecyclerView.ViewHolder {
...
RelativeLayout myLayout = (RelativeLayout) v.findViewById(R.id.device_adap_layout);
myLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context cxt = myLayout.getContext();
final Intent i = new Intent(cxt, NextActivity.class);
i.putExtra("ITEMNAME", mAdapterList.get(getAdapterPosition()));
cxt.startActivity(i, options.toBundle());
}
});
...
}
Create adapter class which extend Recycle view and override needed method:
public class Adapter extends RecyclerView.Adapter
"<"Adapter.AdapterViewHolder">" {
public List<Object> Items;
private Context context;
public Adapter(List<Object> items, Context context) {
Items = items;
this.context = context;
}
#Override
public int getItemCount() {
return comentsItems.size();
}
#Override
public void onBindViewHolder(final AdapterViewHolder hd, int position) {
int indexOfCard = position;
hd.itemText.setText("pos: "+ position);
}
#Override
public AdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.
from(viewGroup.getContext()).
inflate(R.layout.item_layout, viewGroup, false);
return new AdapterViewHolder(itemView);
}
public static class AdapterViewHolder extends RecyclerView.ViewHolder {
protected TextView itemText;
public AdapterViewHolder(View v) {
super(v);
itemText = (TextView)v.findViewById(R.id. itemText);
}
}
}
You should set the onClickListener in onBindViewHolder where you already have the position:
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
listener.onItemSelected(position);
}
}
});
}
EDIT:
Like #tyczj says, for the RecyclerView it's better to use getAdapterPosition in ViewHolder.
When you populate the cardView with your data, you can also use the View's setTag() method to store the position. Since you will get the View when onClick is called, you can simply call getTag() on the View to retrieve the position.
I am using a Listview. before implementing OnLongClick, my onListItemClick was working perfectly, however now, after implementing OnLongClick the long clicks work and normal list clicks don't do anything. It seems to hide exposure to the onListItemClick() function you already have working
can anyone see why/ suggest a solution?
public class CombChange extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ListEdit(this, symbols));
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selectedValue = (String) getListAdapter().getItem(position);
if (lastPressed.equals(selectedValue) ){
count++;}
}
public class ListEdit extends ArrayAdapter<String> implements OnLongClickListener{
private final Context context;
private final String[] values;
public ListEdit(Context context, String[] values) {
super(context, R.layout.activity_comb_change, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.activity_comb_change, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values[position]);
rowView.setOnLongClickListener(new OnLongClickListener(){
public boolean onLongClick(View arg0) {
context.startActivity(new Intent(context,RestoreOriginal.class));
return false;
}
});
// Change icon based on name
String s = values[position];
if (s.equals("a")) {
imageView.setImageResource(R.drawable.a);
return rowView;
}
}
I think you shouldn't do rowView.setOnLongClickListener.
Try something likes this:
this.getListView().setLongClickable(true);
this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
// whatever you wanna do
return true;
}
});
I took the code from how to capture long press event for Listeview item of a ListActivity?
Hope this helps.
i m developing an application in which gridview contain list of button...
when i place images instead of button in gridview then onItemClickEvent get fired..but if i place button in gridView then click event not getting callled...i dont know what is the problem...even i m not getting exception..
here is my code...
public class MainMenu extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.mainMenu);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
Toast.makeText(MainMenu.this, "hello" + position, Toast.LENGTH_SHORT).show();
}
});
}
//inner class for adapter
class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c)
{
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
//ImageView imageView;
Button btn;
if (convertView == null) { // if it's not recycled, initialize some attributes
btn=new Button(mContext);
// imageView = new ImageView(mContext);
btn.setLayoutParams(new GridView.LayoutParams(120,120));
// imageView.setLayoutParams(new GridView.LayoutParams(140,140));
//imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
btn.setPadding(10,15, 10,15);
btn.setImeActionLabel("hello",0);// actionId)
// imageView.setPadding(8,8, 8, 8);
} else
{
btn=(Button)convertView;
//imageView=(ImageView)convertView;
}
btn.setBackgroundResource(mThumbIds[position]);
//imageView.setImageResource(mThumbIds[position]);
//return imageView;
return btn;
}
// references to our images
private Integer[] mThumbIds =
{
R.drawable.pantrylocator_icon,
R.drawable.volunteeropportunity_icon,
R.drawable.volunteerlocator_icon,
R.drawable.volunteermanagement_icon,
R.drawable.donationform_icon,
R.drawable.donationviamsg_icon,
R.drawable.donationvideo_icon,
R.drawable.virtualfooddrive_icon,
R.drawable.newevent_icon,
R.drawable.pressrelease_icon,
R.drawable.volunteerphotos_icon,
R.drawable.aboutus_icon,
};
}
}
The button has its own OnClickListener:
public View getView(int position, View convertView, ViewGroup parent) {
//ImageView imageView;
Button btn;
if (convertView == null) { // if it's not recycled, initialize some attributes
btn=new Button(mContext);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
// imageView = new ImageView(mContext);
btn.setLayoutParams(new GridView.LayoutParams(120,120));
// imageView.setLayoutParams(new GridView.LayoutParams(140,140));
//imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
btn.setPadding(10,15, 10,15);
btn.setImeActionLabel("hello",0);// actionId)
// imageView.setPadding(8,8, 8, 8);
} else
{
btn=(Button)convertView;
//imageView=(ImageView)convertView;
}
btn.setBackgroundResource(mThumbIds[position]);
//imageView.setImageResource(mThumbIds[position]);
//return imageView;
return btn;
}
In your ImageAdapter-> getView method add the following line before returning newly created "convertView"
convertView.setClickable(false);
convertView.setFocusable(false);
If any of the views in gridview are clickable then they will block the grid's ItemClick listener from responding.
There is no onclick event written for the Buttons you are adding. Write code for the buttons to handle the click event! let us know then.
i have fece this problem also but finally got the solution i have follow the above suggession
and define button click event in base adapter class like as
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v;
if(convertView==null){
LayoutInflater li = LayoutInflater.from(mContext);
v = li.inflate(R.layout.icon, null);
tv = (Button)v.findViewById(R.id.icon_text);
iv = (ImageView)v.findViewById(R.id.icon_image);
iv.setImageResource(mThumbIds[position]);
tv.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(mContext, "vim", Toast.LENGTH_LONG).show();
}
});
}
else
{
v = (View)convertView;
}
return v;
}
gridview = (GridView) findViewById(R.id.gameGrid);
gridview.setAdapter(ia);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Ur Code here
}
Add click events for the button added in gridView
Here's the cleanest way to do it: call performItemClick() on the GridView from within each button's click listener. That way you can still use the GridView's onItemClickListener like normal.
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
...
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((GridView) parent).performItemClick(v, position, 0);
}
});
}
http://www.migapro.com/click-events-listview-gridview/
I have solved my problem as i define button click event in base adpter class and my problem is solved......