'How to add a button with image and text dynamically in Android GridView?
I want to add ImageButtons
with text dynamically to a GridView
(Something like below) and also set a listener
such that a user enter a different page, when he clicks on an icon. The buttons will need to fill up horizontally first so I think I will need 2 loops. I have searched but I can't find a good tutorial on how to do this.
(source: botskool.com)
How I intend to do it
ArrayList<String> options = getOptions();
for(int i=0; i<options.size(); i++){
String opt = options.get(i);
if(opt.equals("Contacts")){
//Add Contacts button with image in GridView
Button btn = new Button(this);
//Set button text
//Set image
//Set listener to go to another activity
layout.addView(btn);
}else if(..){
//Add another button with image in GridView
//Set button text
//Set image
//Set listener to go to another activity
}
}
I would really appreciate if someone can guide me on how to set ButtonImage
, Button Text
and listener
all together dynamically in a GridView
. Thanks in advance!
Solution 1:[1]
Create xml file and take Gridview in it and even Textview reference it in the class/java file you wnat to use
Now when you use the grid view you will use the imageadapter and extends the base adapter while in that you will have the getview() function where u set the image source dynamically and even set the Textview every time
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dharman |