Android: Creating a custom Adapter for GridView (ButtonAdapter)
Background
Adapters are great, it’s a fact. After you get over the initial learning curve you will realise you love them (almost as much as a six sided companion). This is my attempt at a casual explanation of how to create your own custom adapter, in this example we will create a ButtonAdapter similar to something you might see in a soundboard (yawn).
Advantages of an adapter
- Dynamic – Can expand to any number of elements rather than statically coding each individual view.
- Elegant – Makes your code petite and quite clear to understand once you get over the initial difficulty
- Beautiful – Now you don’t have to control how many items there are in rows or columns, android will automatically fill up the screen in the best way possible. This also means you don’t need to redesign your application for horizontal and vertical orientations.
Creating a ButtonAdapter
So we’re going to dive straight into the deep end and create our own ButtonAdapter class that extends the BaseAdapter class. If you are doing this in eclipse you can write the first line and then it will offer to autocreate (implement) the missing methods for you (if you highlight the error). This code goes inside your Activity in your java file but not inside your oncreate method.
public class ButtonAdapter extends BaseAdapter { private Context mContext; // Gets the context so it can be used later public ButtonAdapter(Context c) { mContext = c; } // Total number of things contained within the adapter public int getCount() { return filenames.length; } // Require for structure, not really used in my code. public Object getItem(int position) { return null; } // Require for structure, not really used in my code. Can // be used to get the id of an item in the adapter for // manual control. public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { Button btn; if (convertView == null) { // if it's not recycled, initialize some attributes btn = new Button(mContext); btn.setLayoutParams(new GridView.LayoutParams(100, 55)); btn.setPadding(8, 8, 8, 8); } else { btn = (Button) convertView; } exus btn.setText(filesnames[position]); // filenames is an array of strings btn.setTextColor(Color.WHITE); btn.setBackgroundResource(R.drawable.button); btn.setId(position); return btn; } }
So the important methods are getCount and getView. getCount returns the number of objects (in our case buttons) that will be needed in this adapter. getView returns an object (again a button in our case) so that it can be used.
Both these functions reference an array that I have referered to as filenames this is a string array (String[]) which looks something like the following:
public String[] filesnames = { "File 1", "File 2", "Roflcopters" };
Creating an OnClickListener
You can add the following to your getView method to setup a new onclick listener for your buttons so that they can react to button presses.
// Set the onclicklistener so that pressing the button fires an event // We will need to implement this onclicklistner. btn.setOnClickListener(new MyOnClickListener(position));
For this to work we need to implement our own OnClickListner which I have named MyOnClickListener (for lack of a better name) this is the same as a normal onclick listner except we pass an integer so that we can tell which button called our onClick method (you could get the id from the view passed, but this method is useful when expanding your program later on).
class MyOnClickListener implements OnClickListener { private final int position; public MyOnClickListener(int position) { this.position = position; } public void onClick(View v) { // Preform a function based on the position someFunction(this.position) } }
Implementing this adapter
Now implementing the adapater is very simple, add a few imports and load a grid view from an xml file. Then we simply set the gridview’s adapter to be a new ButtonAdapter and it will automatically do the rest for us.
// You will need the following imports import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; // In your oncreate (or where ever you want to create your gridview) GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ButtonAdapter(this));
And hopefully your all done, you could then go on to add a context menu(menu on long press) to your buttons. If you have any questions or want something explaining a bit better, just ask!