I have a super TestUI application. It has a gridview with buttons in them.
I want word of the button click to be passed back to the main Activity, so that it can update its state.
Sadly the buttons steal the clicks. So the typical:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(TestUI.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
Does not get called.
Instead in the adapter definition:
public View getView(int position, View convertView, ViewGroup parent) {
Button gridItem;
if (convertView == null) { // if it's not recycled, initialize some attributes
gridItem = new Button(mContext);
} else {
gridItem = (Button) convertView;
}
gridItem.setText("button " + String.valueOf(position));
gridItem.setClickable(true);
gridItem.setFocusable(false);
gridItem.setOnClickListener(new MyOnClickListener(position, mContext));
return gridItem;
Which is backed with a class MyOnClickListener that implements the OnClickListener interface. However if I do it this way I still need a call back to the main activity, somehow it needs to know that something was done as it controls the program state.
So what is the best way to update the “root” class/activities’ state from a button click?
I know this a basic OO question but I mostly write in ASM and C so I frankly just don’t know.
As you said, your getView method is inside the adapter class. But the adapter gets a copy of the “context”, which your getView method has access to. Context is a super-class of all Activities and Services. Through this object you can do many of the basic operations of an Activity. From your example, I understand that you would like to show a toast. This can be done using
So in short, your MyOnClickListener class needs to used the mContext variable for interacting with the root activity.
Edit
I realized that I made a mistake in the above answer. I looked at the sample on http://developer.android.com/resources/tutorials/views/hello-gridview.html and realized that you aren’t restricted to using Context. You could use something like
Hopefully that is what you wanted to do.