Creating an array of buttons programatically in android - android

I am currently learning android and I am trying to create an array of buttons for my app in the following manner:
LinearLayout answer_layout = (LinearLayout)findViewById(R.id.answer_layout);
idCount = answer_layout.getId() + 1000;
for(int i = 0 ; i<letters.length ; i++)
{
Button b = new Button(this);
b.setText(letters[i]);
b.setTypeface(null, Typeface.BOLD);
b.setBackgroundResource(R.drawable.puzzletilebg);
b.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
b.setIncludeFontPadding(false);
b.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
b.setId(idCount + i);
b.setTag(Integer.valueOf(i));
bLetters[i] = b;
answer_layout.addView(b);
}
}
When i run this code, i am able to get a row of buttons depending on the length value of string. My problem is the buttons appear stretched and when the length value is more than 7, The buttons dont appear. For this problem i tried implementing the method suggested here(How do I programmatically add buttons into layout one by one in several lines?) but i didnt get any result. What parameters do i have to use to make the shape of the buttons as a perfect square and make sure they are of the same size for all screen sizes? My button background drawable size is 50x50.

If you want a perfect square change
LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
to
LinearLayout.LayoutParams(50, 50);
And ofc if your linearLayour is horizontal the buttons will dissapear
on the edge of the screen.
You can use Gridlayout instead of LinearLayout, but if you want something like the LinearLayout i recommend: FlowLayout
example:
Last edit: sorry is not AutoFitLayout is FlowLayout i edited the answer;
Solve your problem?

Instead of LinearLayout use a GridLayout

Try with
b.setWidth(50);
b.setHeight(50);
The numbers are pixels, so maybe you have to convert dp to pixels.

For the problem with button more than 7 not appear, you could try to wrap your LinearLayout answer_layout in a ScrollView or HorizontalScrollView for horizontal scroll behaviour in the xml file.
And for programmatically change the width and the height of the button, you could try this answer https://stackoverflow.com/a/11294075/1331743
from existing post.

Related

Android: Imagebutton I set programatically are distored in size

this is like the x-time that I am doing this however today nothing works.
Im basically doing this:
ImageButton btnComments = new ImageButton(this);
ImageButton btngreenLikes = new ImageButton(this);
ImageButton btnblueLikes = new ImageButton(this);
btnComments.SetBackgroundResource(Resource.Drawable.comments_small);
btngreenLikes.SetBackgroundResource(Resource.Drawable.upvote_green);
btnblueLikes.SetBackgroundResource(Resource.Drawable.upvote_blue);
LinearLayout.LayoutParams lpWrap = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WrapContent, LinearLayout.LayoutParams.WrapContent);
btnComments.LayoutParameters = lpWrap;
btngreenLikes.LayoutParameters = lpWrap;
btnblueLikes.LayoutParameters = lpWrap;
linlayForImages.AddView(btnComments);
linlayForImages.AddView(btngreenLikes);
linlayForImages.AddView(btnblueLikes);
Set add thre imagebuttons in within my code. Give all three a background resource, then set their layout to WRAP CONTENT in HEIGHT and WIDTH.
And then add their views into my layout.
The result ist, they are everything BUT wrapped content. While the comment img is correct, th other two are distored. greenlikes is too big in total size and blue like is top big in width? I use those imagebutton resources in another activity where I set those with the xml and they are fine. So the resource is all clear. Can someone tell me what the HELL is going on here?
Update: Naming my Imagebuttons Imageviews solved this issue. Don't!

Views are not aligned in an horizontal LinearLayout

In a ListView getview() method, I build my layout like this :
LinearLayout layout = new LinearLayout(context);
layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 200));
layout.setWeightSum(120);
for (int i = 0; i < totalTVNumber; i++) {
LifeEvent event = getEventFromDB(cost, position);
if (event != null) {
TextView eventTV [![enter image description here][1]][1]= event.getTextView(getContext());
eventTV.setLayoutParams(new LinearLayout.LayoutParams(0, 200, getTheWeight(eventTV)));
layout.addView(eventTV);
}
}
The problem is that doing this will cause my view not to be exactly aligned vertically. Since they have the same height than the layout, I expected them to match it but some views (nearly 1 on 2) act like they have a little margin-top. Of course there is nothing like a margin-top in my code, and reading their margin onClick returns 0.
Adding layout.setGravity(Gravity.TOP); doesnt change anything, and adding eventTV.setGravity(Gravity.TOP); just put the text on the top of the TV.
Note that if I go for MATCH_PARENT intead of 200 for the event, it acts exactly as expected, but I would like the views to be a little smaller than the layout, to get a little gap between them.
In case it matters, a LinearLayout can have from 2 to 9 textviews inside, and their weight are calculated to sum to 120 (for instance 44+34+2+40). Horizontal behaviour is ok.
How can I align view on the top of my horizontal linearlayout ?
EDIT : here is a screenshot :

android set width and height to 100% of a dynamically created button

that might be a silly question but i didn't find any answer on the internet.
I want to create a button that fills the whole screen (width = 100%, height = 100%) when pressing another button.
Therefore i tried this:
Button button = new Button();
button.setText("fills screen");
button.setWidth(100);
button.setHeight(100);
the problem is that the setWidth and setHeight methods are dealing with px and not with percent.
What do i need to add to use percent values instead of px values?
I'll link here a post that details how to set a width programmatically
programmatically set button width to 50 of parent linearlayout
You can utilize that method (except do not divide by 2 JohnEye demonstrates in his answer)
Or you can utilize the LayoutParams class and create a new instance that will have the parameters set and pass those parameters to your object.
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
button.setLayoutParams(lp); // Assuming you've already initiated it of course as above
MATCH_PARENT will fill up the view. If the root view is the highest view on the hierarchy then this will work, as it will fill up the entire view. If not, the button would need to be moved there. (It may be your linearLayout or some other view)
Hope this helps.

Layouts and Button

TableLayout relativeLayout = (TableLayout)findViewById(R.id.ll1);
TableRow row =new TableRow(this);
Button button ;
int counter = 0;
for(int i = 0;i<=13;i++){
counter++;
button = new Button(this);
button.setText(counter);
row.addView(button);
}
relativeLayout.addView(row,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
relativeLayout.computeScroll();
XML File
<TableLayout android:id="#+id/ll1" android:shrinkColumns="true"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="#id/button1"
xmlns:android="http://schemas.android.com/apk/res/android"></TableLayout>
But whenever i execute my application it just move my buttons in a single row and after 5 buttons all the buttons move out from the screen. i dont' want to add more rows as i don't want to hard-code anything in my code like placing some code if (counter%5==0) then do this and that.
Is there any other way to calculate the width that if the buttons are equivalent to the width of screen then do this or that or any other way like any property in table Layout which simply wrap content of a row?
Yes there is a way to get the exact width of any component in your app. Look at my answer to my question asked a while ago here. As you can see, I instantiate a Paint object, but that's not necessary unless you wish to get the width of the text itself. However you must use the density multiplier:
float scale = getContext().getResources().getDisplayMetrics().density;
That will convert any function that gets the width of a component (in this case, your button) to the actual pixel width on any given devices. So you would get the button width (via invoking the getWidth() function on your Button object) and then multiply by that scaling factor.
Use FlowLayout instead:
http://nishantvnair.wordpress.com/2010/09/28/flowlayout-in-android/
GIT project:
https://gist.github.com/1073863
Using Contex's method getResources() you can access all the resources for your application's package. The method returns Resources and you can see here all properties that are available.

How do I achieve square layout and buttons in main.xml?

I would like to have a layout with 5 times 5 buttons. Each of them should have the same width and height (they should be square). And I want the whole matrix to use the screen width (or height, depending on rotation).
I currently do it "by hand" in the Java code:
for (int y=0; y<5; y++) {
TableRow tr = new TableRow(this);
for (int x=0; x<5; x++) {
Button b = new Button (this);
...
tr.addView(b, 60, 60);
}
layout.addView(tr);
}
This can be improved by obtaining screen width first and then dividing by 5 to get rid of this literal 60. But I'm wondering how I can do this in the res/layout XML file?
How can I specify for the height to be the same as the width? (I can set the width to match_parent.)
You are best off just doing this as a custom layout manager. Subclass from ViewGroup and implement the desired layout code. It is quite simple to implement a custom layout manager if you are trying to do a general-purpose layout algorithm (which you aren't).
See for example the platform's AbsoluteLayout as an example of a simple layout manager: https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/widget/AbsoluteLayout.java
I've two ideas.
Both are pretty similar to suggestion from hackbod
Instead of implementing subclass from ViewGroup, you can create something like SquareButton extending Button or SquareTableLayout extending TableLayout.
Override constructor class, so that you will replace the width or height value with the smallest value of them both. I'm not sure, but i guess, you'll be able to use new Layouts in XML-Description.
Probably it's easier to create just a SquareTableLayout
Then just set width and height of all elements within TableLayout to 0dip and the weight of all of them to 1.
Assuming that you have NxN elements in your Table, they all will get then the same width and the same height because of the same weigth.
Use Tables... that way all the buttons are same width. you can change height accordingly
You'll want to check out a TableLayout.

Categories

Resources