Android: How to add buttons to GridView dynamically? - android

I am trying to add buttons to a GridView for each string from textArray.
void addButtons() {
GridView gridView = (GridView) findViewById(R.id.gridView);
List<Button> buttons = new ArrayList<Button>();
for (int i = 0; i < textArray.length; i++) {
Button newButton = new Button(this);
newButton.setText(textArray[i]);
newButton.setId(i);
newButton.setOnClickListener(onClickListener);
buttons.add(newButton);
}
ArrayAdapter<Button> arrayAdapter = new ArrayAdapter<Button>
(this, android.R.layout.simple_list_item_1, buttons);
gridView.setAdapter(arrayAdapter);
}
But in result, I get this: Virtual Device screen
What can be wrong? Or maybe there is a better way to do the same thing? I've tried LinearLayout and everything was ok, but I was not able to scroll down.
how to add button in gridview dynamically might have a solution, but, to be honest, it is too hard for me at the moment.

Try this out, it shows how to create buttons during runtime https://forums.xamarin.com/discussion/49225/dynamic-buttons-in-gridview

So the initial problem was to get a view with programmatically generated buttons. The first solution was a LinearLayout, but I found out that I was not able to scroll it down, so the number of buttons was limited. On the internet, I found that GridView also can do such a task and it would be scrollable. Well, it is true, but I have stuck upon the problem mentioned in this thread.
After a few days of googling I found that LinearLayout inside ScrollView is what I need. So here is both my xml and java code for someone who stumbles up on the same problem:
<ScrollView
<LinearLayout
android:id="#+id/cityLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<!-- Content here -->
</LinearLayout>
</ScrollView>
void addButtons() {
LinearLayout linearLayout = findViewById(R.id.cityLayout);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
for (int i = 0; i < cityArray.length; i++) {
Button newButton = new Button(this);
newButton.setText(cityArray[i]);
newButton.setId(i);
newButton.setOnClickListener(onClickListener);
linearLayout.addView(newButton, layoutParams);
}
}
Anyway, thanks to everyone for help!

Related

Setting Some TextView's Text

In my Project , I have 80 TextViews.
I should set their text from 1 to 80 once project runs , and they dont need to be changed in future.
Except TxtViews , I have some other things in my Layout, the TextViews are under ImagesViews. actually I have 80 imagesViews and under them are 80 TextViews. I want to set text of textViews from 1 to 80 dynamically.
I know I can do it in my layout.xml ,
but its really time consuming.
is there any way to do that by code?
for example with a for cycle or something like that?
Create a ViewGroup suitable for your needs in the layout, for example:
<LinearLayout
android:id="#+id/linear_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
Then you create you TextView instances programatically, and add them to the LinearLayout, like this:
LinearLayout layout = (LinearLayout)findViewById(R.id.linear_layout);
for(int i = 0; i < 80; i++) {
TextView textView = new TextView(getContext());
textView.setText("text" + i);
layout.addView(textView);
}
Optionally, you can add tags or whatever to locate them again. Alternatively just iterate over the layouts subviews.
If you know that 80 Textview fixed then you should take listview for that.
Listview Benefit
Memory management automatically
Listview manage indexing
If they share the same layout, except for the text, and could be displayed as a list, you could use an ArrayAdapter and pass the values from code.
http://www.mkyong.com/android/android-listview-example/
Checkout the below example,
public class MainActivity extends Activity {
LinearLayout linearLayout ;
ScrollView scrollView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scrollView = (HorizontalScrollView) findViewById(R.id.scrollViewActivityMain);
}
private void populateTextViews() {
linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
//add all textViews here
for(int i=0; i < 80; i++){
TextView myTextView = new TextView(this);
myTextView.setText("My TextView "+i);
myTextView.setGravity(Gravity.CENTER);
linearLayout.addView(myTextView);
}
scrollView.addView(linearLayout);
}
}
Don't forget to put that scrollView in your xml.
Let me know if it works for you...
If your TextViews are declared on the xml, wrap them on another view so you can reference it on the java code later, then simply use a for.
Something like:
View view = findViewById(R.id.your_wrapper);
for(int i=0; i<((ViewGroup)view).getChildCount(); i++) {
View nChild = ((ViewGroup)view).getChildAt(i);
TextView tv = (TextView) nChild;
tv.setText(String.valueOf(i + 1));
}
If not, you can simply create them dynamically inside your java code, and append them to a layout like LinearLayout.
Example:
xml
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/linear"
/>
Java code
LinearLayout ll = (LinearLayout) findViewById(R.id.linear);
for (int i = 1; i <= 80; i++) {
TextView tv = new TextView(this); // Assuming you're inside an Activity.
int count = ll.getChildCount();
tv.setText(String.valueOf(i));
ll.addView(tv, count, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
EDIT: But truly, you should use RecyclerView or ListView for that if your values are not going to change.
You can read more about RecyclerView here, and on ListView here.
Second edit: From what you're saying on your comments, you REALLY should be using ListView instead of your current design. The solutions above and from the other answers won't work at all for your problem.

Rows of buttons with LinearLayout

I need to place a dinamic number of buttons in some rows. The number of buttons per row and the size should fit to any screen width.
LinearLayout llh = new LinearLayout(this);
llh.setOrientation(LinearLayout.HORIZONTAL);
for(int i=1; i<=nl; ++i) {
Button b = new Button(this);
b.setText(String.valueOf(i));
if(i>ul) {
b.setFocusable(false);
b.setEnabled(false);
}
llh.addView(b);
}
The problem with this piece of code is that for example, my nl test value is 10, and this only displays 6 buttons, all in the same row, and the last one is smaller than the others.
I need them to stack vertically, like, when there's no space for another button, a new row is created and the rest of the buttons go in there.
Thanks in advance.
Sounds like you are talking about a vertical FlowLayout, where newly added views are stacked vertically until there is no more room, then a new column is started.
Unfortunately Android does not already have a FlowLayout, but you can make your own. Check out this answer by Romain Guy "How can I do something like a FlowLayout in Android?", and watch the video of his talk where he describes how to create one. I learnt a great deal about creating custom layouts by watching this several times until I understood it.
If the width of the screen is less than a certain value, set the weight property to 1 for all buttons. And if the screen width is large enough to fit all your buttons properly, go with the default.
I cannot post the code now as I am far away from my PC.
This is what I came up with. It's not as pretty as I tought but it gets the job done.
Buttons will have fixed size, but that shouldn't be much of a problem.
Thanks for all your help :)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="top|center_horizontal"
android:orientation="vertical"></LinearLayout>
Display display = getWindowManager().getDefaultDisplay();
Point p = new Point();
display.getSize(p);
int buttonSize = 120;
int n = p.x/buttonSize-1;
LinearLayout llv = (LinearLayout)findViewById(R.id.container);
LinearLayout llh = null;
for(int i=0; i<nl; ++i) {
Button b = new Button(this);
if(i%n==0 || i==0) {
llh = new LinearLayout(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llh.setLayoutParams(params);
llh.setOrientation(LinearLayout.HORIZONTAL);
llv.addView(llh);
}
b.setText(String.valueOf(i+1));
b.setWidth(buttonSize);
if(i>ul) {
b.setFocusable(false);
b.setEnabled(false);
}
llh.addView(b);
}

How to add Buttons dynamically into ScrollView

I'm having a difficulty adding buttons dynamically to a ScrollView. The code below is adding the buttons BUT there is no scroller.
If I'm putting the buttons directly in the XML (not dynamically) it's working and I can scroll down/up.
My view:
<ScrollView android:id="#+id/ScrollView01"
android:layout_width="264dp"
android:layout_height="match_parent"
android:fillViewport="true"
>
<LinearLayout
android:id="#+id/buttons"
android:layout_width="264dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:scrollbars="vertical"
>
** HERE THE BUTTONS SHOULD BE ADDED DYNAMICALLY **
</LinearLayout>
</ScrollView>
The code which adding buttons:
// create new button
final Button newbutton = new Button(this);
// set background color
newbutton.setBackgroundColor(Color.GRAY);
// set width and height
newbutton.setWidth(50);
newbutton.setHeight(20);
// set position
newbutton.setY(((float)numOfButton*20)+20);
newbutton.setX(100);
// set text
newbutton.setText(Integer.toString(numOfButton));
// create patameter
final LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);
//set listener
android.view.View.OnClickListener buttonListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// make all the DrawView invisible
for(View view : comments){
view.setVisibility(View.INVISIBLE);
}
// set the chosen comment visible
comments.get(numOfButton).setVisibility(View.VISIBLE);
boardsHandler.setCurrenBoard(numOfButton);
}};
newbutton.setOnClickListener(buttonListener);
// creating a thread to add button
buttons.post(new Runnable() {
#Override
public void run() {
buttons.addView(newbutton, p);
}
});
Is it something with the LinearLayout.LayoutParams p ?
Thanks!
Try following code
first do
LinearLayout myContainer = findViewById(R.id.layoutId);
When you set parameters for a view, they need to correspond to the parent view for your widget.
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.FILL_PARENT);
finally add button as you are doing.
try and tell if it works
Setting X and Y position will not work. The LinearLayout layouts it's children vertically or horizontally, only taking their width/height into account.
Besides this -- have you tried calling buttons.invalidate() after buttons.addView(...). This should refresh the layout and should show your newbutton.
This is a rather old post but I found it quickly when doing research on that kind of problem. So I'll post am answer anyway, maybe it'll be of help to anyone..
I had a similar problem with a relative layout to which buttons were added dynamically. I found a workaround in defining the layout's size manually when adding the buttons. For your case, adding the line
buttons.getLayoutParams().height = numOfButton*20+40;
after
buttons.addView(newbutton, p);
might help, though it's probably not the best solution.
I thought my mistake was using the RelativeLayout at all, but since you appear to have the same problem...
Ever thought of using a table layout?

Nesting layouts and dynamically updating them

I want to nest a TableLayout inside a RelativeLayout and later dynamically edit the TableLayout in my Java Code.
My XML-File looks like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_load_date"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LoadDateActivity" >
<!-- few buttons and textviews -->
<TableLayout
android:id="#+id/activity_load_date_table_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button" >
</TableLayout>
</RelativeLayout>
Java Code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_load_date);
//Do something with my Buttons and TextViews(this works fine)
tblLayout = (TableLayout) findViewById(R.id.activity_load_date_table_layout);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.button_calc) {
for (int i = 0; i < listOfEntries.size(); i++) {
Entry temp = listOfEntries.get(i);
if (temp.getDate().getTime() >= startDate.getTime()
&& temp.getDate().getTime() <= endDate.getTime()) {
TableRow tr = new TableRow(this);
TextView comm = new TextView(this);
comm.setText(listOfEntries.get(i).getComment());
TextView val = new TextView(this);
val.setText(String.valueOf(listOfEntries.get(i).getValue()));
LayoutParams params = new LayoutParams(0,
LayoutParams.WRAP_CONTENT, 1f);
tr.setLayoutParams(params);
tr.addView(comm);
tr.addView(val);
tblLayout.addView(tr);
}
}
tblLayout.invalidate(); //Shouldn't this redraw the entire TableLayout and therefore adding my TableRows? This is not working.
}
}
Through various tests with TextViews and Toasts I have gathered that the tblLayout should be filled and the TableRows are added to the Layout, the only thing that is not working is the "repainting" of my Layout. How do I achieve that?
Edit:
Apparently the thing that made this not work was actually the LayoutParams given to the TableRow, once I commented those out I atleast got it printed to the screen. They are however not where I expect them to be.
I expected them to be below the buttons, instead they are in the top left corner on top of the buttons. This leads me to believe that the TableLayout is actually the same size as the RelativeLayout but is layered above the RelativeLayout. The error should therefor lie in my XML-File. What height do I need to give my TableLayout to make this work the way I expect?
Edit2:
I needed to add the android:layout_below attribute to my TableLayout, works as a charm now!
You need to call the method "requestLayout()"
Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree.

How to create a shelf like view in Android?

How to create a shelf like view in android that show several book in any row? Also, it should have horizontal and vertical features like the moon+reader app has.
I can write a shelf view that moves horizontally but it doesn't fully work. I used a xml file for view items that included image, text and button. I wrote a class that extends AdapterView to create a customized ListView that I called "shelf view". Unfortunately, my program show one row and I can't use it for several row.
Last Updated: Now, I can detect a new way for create shelf-view better than the previous solution. I described it in CodeProject
By the Way, In this application I used two classes:
HorizontalListView Class that extends the AdapterView. It downloaded from GitHub
Quaere library use almost same as Linq2Object in .Net. You can download here.
Apr 22 '12:
There are some ways to implement shelf view that it have two features(horizontal & vertical scroll). I try to write a program that can run dynamically. This sample App have a XML file and a showShelfView java class.
So you can see my App:
main XML file: First, Add following code in main.XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/sclView">
<TableLayout
android:id="#+id/tblLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0dp">
</TableLayout>
</ScrollView>
showShelfView Class: Inner TableLayout add several HorizontalScroll equals with number of rows. Also inner any TableRow add Image.
Don't forget set a shelf image for Row's background:
public class showShelfView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
int numRow = 4;
int numCol = 8;
TableLayout tblLayout = (TableLayout) findViewById(R.id.tblLayout);
for(int i = 0; i < numRow; i++) {
HorizontalScrollView HSV = new HorizontalScrollView(this);
HSV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
TableRow tblRow = new TableRow(this);
tblRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tblRow.setBackgroundResource(R.drawable.bookshelf);
for(int j = 0; j < numCol; j++) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.book1);
TextView textView = new TextView(this);
textView.setText("Java Tester");
textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tblRow.addView(imageView,j);
}
HSV.addView(tblRow);
tblLayout.addView(HSV, i);
}
}
}

Categories

Resources