Android align set of buttons programatically in layout - android

the thing which I want to achieve in my application is to create dynamically a set of buttons with different text size and after that align these view inside a linear layout. Here is a sample of what I want to achieve :
. Depending on the textsize I want the buttons to be align in a single line, if the last button is bigger than the screen size, it should properly go to the next line.
Any suggestions how can I achieve this or what should I look for, because I know that if I try button.getWidth(); it will return 0 and it won't work.
Thanks for any kind of suggestions!
EDIT
To achieve this you can use a new layout open sources by Google called: FlexboxLayout. You can learn more about it in this post from Android Developers Blog.

Thanks to #Kameswari 's code which gave me the right direction I achieve this by using :
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(5, 5, 5, 5);
String[] mKeywordsArray = mKeywords.split(", ");
if(mKeywordsArray != null){
LinearLayout mNewLayout = new LinearLayout(getActivity()); // Horizontal layout which I am using to add my buttons.
mNewLayout.setOrientation(LinearLayout.HORIZONTAL);
int mButtonsSize = 0;
Rect bounds = new Rect();
for(int i = 0; i < mKeywordsArray.length; i++){
String mButtonTitle = mKeywordsArray[i];
Button mBtn = new Button(getActivity());
mBtn.setPadding(10, 3, 10, 3);
mBtn.setText(mButtonTitle);
Paint textPaint = mBtn.getPaint();
textPaint.getTextBounds(mButtonTitle, 0, mButtonTitle.length(), bounds);
// size of all buttons in current horizontal layout
// i am using +45 because of extra padding which is set in xml for this layout
mButtonsSize += ( bounds.width() + 45);
if(mButtonsSize < (mScreenWidth - 32)){ // -32 because of extra padding in main layout.
mNewLayout.addView(mBtn, params);
} else {
mButtonsLayout.addView(mNewLayout);
mNewLayout = new LinearLayout(getActivity());
mNewLayout.setOrientation(LinearLayout.HORIZONTAL);
mButtonsSize = bounds.width();
mNewLayout.addView(mBtn, params); // add button to a new layout so it won't be stretched because of it's width.
}
}
mButtonsLayout.addView(mNewLayout); // add the last layout/ button.
}

You can try the following
While adding the buttons you can calculate the how much width till occupied as
occupiedWidth = button1Width + button2Width + ...
Every button width = textWidth + 2*margin + 2*padding
You can get your width of the text which you put on the button like
String buttonText = "<Your Button Text>"
paint.getTextBounds(buttonText, 0, buttonText.length(), bounds);
int textWidth = bounds.width();
Add this new button margins and paddings as
int newWidth = textWidth + buttonMargin*2 + buttonPadding*2;
if the total width is exceeding the screenwidth then move to next row.

According to me, you have 2 options:
1) Take a linear layout with horizontal orientation.
and keep adding buttons to this layout programmatically.
if the width of the button is not able to fit in the line, it will automatically go to next line in linear layout.
ViewGroup linearLayout = (ViewGroup) findViewById(R.id.linearLayoutID);
Button bt = new Button(this);
bt.setText("A Button");
bt.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
linerLayout.addView(bt);
2) You can calculate x,y location of each button as mentioned by #kameswari and draw corresponding button at x,y location
Button button = (Button)findViewById(R.id.button);// or new Button(this);
AbsoluteLayout.LayoutParams absParams =
(AbsoluteLayout.LayoutParams)button.getLayoutParams();
absParams.x = X;
absParams.y = Y;
button.setLayoutParams(absParams);

u can try this `enter code here`
LinearLayout.LayoutParams leftMarginParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
leftMarginParams.leftMargin = 50;
Button btn1 = new Button(this);
btn1.setText("Button1");
linLayout.addView(btn1, leftMarginParams)

Related

Not able to add margins on buttons through code

Here is my code, I am trying to add few buttons in a row. Its working fine, But these buttons appear too close to each other, I want to apply horizontal margins to buttons. But not able to add. To achieve this I tried to keep button inside a Linearlayout and applied margins to it. But it somehow don't show any buttons, And when I comment out this line- ll.setLayoutParams(lp); Buttons can be seen again, But without any margin. Please let me know how can I make buttons at some distance from each other.
maintable = (TableLayout) findViewById(R.id.maintable);
TableRow tr = new TableRow(this);
for (int z = 0; z < 3; z++) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(5, 5, 5, 5);
LinearLayout ll = new LinearLayout(this);
//ll.setLayoutParams(lp);
Button b = new Button(savedLists.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(150, 150);
params.setMargins(0, 20, 0, 20);
b.setBackgroundResource(R.drawable.circular);
b.setText(Integer.toString(c));
b.setPadding(10,10,10,10);
ll.addView(b,params);
tr.addView(ll);
c++;
}
maintable.addView(tr);
R.drawable.circular is just creating a simple circular button. Please let me know, if I should post that too.
You haven't set any margin for the button here. You are setting it's padding! Here is how you can set the margin for a button!
Button b = new Button(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
params.setMargins(top, left, bottom, right);
yourLinearLayout.addView(b,params);

how to set height and width of the Dynamic button created?

I wanted to create to circle button. So I got the hint from here How to get round shape in Android . As mention in the link it is necessary to have both height and weight of button to be of same size to get shape as circle, otherwise it will be oval shape. We cannot use wrap_content than it will be oval shape.
Buy the problem is now I creating button dynamically and I try to set height and width of button same but still I am getting oval shape button instead of circle.
And I try through xml file keeping button weight and height same it's work, but through dynamic it is not. Below is the code.
for (int count = 1; count <= rowb; count++)
{
tblRow[count] = new TableRow(getApplicationContext());
tbl.addView(tblRow[count]);
for (int j = 1; j <= rowb; j++) {
String nameB=""+i;
btn[i] = new Button(getApplicationContext());
btn[i].setId(i);
btn[i].setText(nameB);
btn[i].setWidth(1);
btn[i].setHeight(1);
tblRow[count].addView(btn[i]);
btn[i].setOnClickListener(getOnClickDoSomething(btn[i],i));
i++;
}
}
notifyAllObservers();
move--;
}
I also try but it also did,t work
TableLayout.LayoutParams lp = new TableLayout.LayoutParams(5,5);
btn[i].setLayoutParams(lp);
Can anybody let me know what the problem is ?How i get tge circle shale button instead of oval ?
You can set width and height by following code:
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tblRow.addView(btnTag);
OR you can also set dp instend of wrap_content in it. like:
Button btnTag = new Button(this);
btnTag.setLayoutParams(new LayoutParams(30, 30));
tblRow.addView(btnTag);
I have this and it worked for me.
final Button bt = new Button(ClassListActivity.this);
bt.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 450));
The first one with MATCH_PARENT is the width. the 450 is the height. Hope it helps!

Dynamic button display programmatically Android

I want to add buttons programmatically on the screen and I am getting the value by parsing an API and now I want to display the buttons according to the length of an array. I am doing this but I am only getting the last button displayed, but inside the for loop I'm getting all values correct but displaying only the last button. This is my code:
RelativeLayout relate;
//...
relate = (RelativeLayout)findViewById(R.id.relative);
protected void onPostExecute(Void result) {
if(dialog.isShowing() == true) {
dialog.dismiss();
}
//int width = 100, height =50, x = 10, y = 20;
for (int i =0;i<adapt_obj.city_name_array.length;i++){
b1 = new Button(myref);
b1.setText(adapt_obj.city_name_array[i]);
relate.addView(b1);
//relate.addView(b1, i, new RelativeLayout.LayoutParams(width,height));
//height = height+80;
}
listlocation.setAdapter(adapt_obj);
adapt_obj.notifyDataSetChanged();
}
A RelativeLayout will stack the views you add to it at the top-let corner if you don't specify some placement rules. Your buttons are added to the layout but they are placed one on top of each other and so the only visible is the last one you add. Here are some modification of your for loop:
RelativeLayout relate; relate = (RelativeLayout)findViewById(R.id.relative);
for (int i = 0; i < adapt_obj.city_name_array.length; i++){
Button b1 = new Button(myref);
b1.setId(100 + i);
b1.setText(adapt_obj.city_name_array[i]);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i > 0) {
lp.addRule(RelativeLayout.BELOW, b1.getId() - 1);
}
b1.setLayoutParams(lp);
relate.addView(b1);
}
You mustn't give x and y values in Android.you can add buttom top left right of an item. Also layout parameters you should use wrap_content or fill_parent.
Button button = new Button(this);
button.setText(#"text");
button.setLayoutParams(new LayoutParams(WRAP_CONTENT,WRAP_CONTENT));
layout.addView(button);
I think the problem is with the relative layout. Your buttons might be getting stack on top of each other. Try making the parent a linear layout.

How to make activity with n buttons same size using RelativeLayout?

I need do design programatically one activity with 6 buttons (same size h and w), and all buttons show a fullsize of activity.
I tried do this: RelativeLayout with buttons and modify for tests.
Show one button!!!
`
setContentView(R.layout.main);
ArrayList<Button> buttons = new ArrayList<Button>();
//RelativeLayout bg = (RelativeLayout) findViewById(R.layout.main);
for (int i = 0; i < 10; i++) {
Button newButton = new Button(this);
newButton.setId(100 + i + 1); // ID of zero will not work
newButton.setText("XXXX");
buttons.add(newButton);
// New layout params for each button
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
if (i > 0) {
// using getId() here in case you change how you assign IDs
int id = buttons.get(i - 1).getId();
lp.addRule(RelativeLayout.RIGHT_OF, id);
}
this.addContentView(newButton, lp);
}`
please look this line if ok: this.addContentView(newButton, lp);
Thanks!!!
mateus
It's a bit not clear from your question whether you want all buttons to distribute evenly across the activity space or each button to take over all activity space?
In first case what you need is a LinearLayout with layout_weight for buttons set to 1.
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
lp.weight = 1;
In the second case I think it's better to use a FrameLayout and just let buttons take over all space by setting
FrameLayout.LayoutParams.FILL_PARENT
to both dimensions.

How to add space between tab buttons in Android?

I need to separate tab buttons with space, I tried to set margin to views and then add them as tabs, but it does not work, I also thought of adding empty view as divider, but haven't tried it yet, is there any standard way of doing this, or any tweak that can achieve same effect?
Thanks!
Here's the way:
TabWidget tabWidget = (TabWidget) findViewById(android.R.id.tabs);
final int tabChildrenCount = tabWidget.getChildCount();
View currentView;
for (int i = 0; i < tabChildrenCount; i++) {
currentView = tabWidget.getChildAt(i);
LinearLayout.LayoutParams currentLayout =
(LinearLayout.LayoutParams) currentView.getLayoutParams();
currentLayout.setMargins(0, 5, 5, 0);
}
tabWidget.requestLayout();
This is really a good solution even for my problem! Many thanks for that! I used it to implement space before the first and after the last item in the widget to have the possibility to scroll them visible to the center without adding additional (and disturbing, because the widget does not excpect such silly things) invisible buttons.
//pump up space for first entry on the left and last entry on the right!
Display display = getWindowManager().getDefaultDisplay();
//Point size = new Point();
int width = display.getWidth();
View currentView = mTabHost.getTabWidget().getChildAt(0);
LinearLayout.LayoutParams currentLayout = (LinearLayout.LayoutParams) currentView.getLayoutParams();
currentLayout.setMargins(currentLayout.leftMargin + width/2, currentLayout.topMargin, currentLayout.rightMargin, currentLayout.bottomMargin);
currentView = mTabHost.getTabWidget().getChildAt(mTabHost.getTabWidget().getChildCount()-1);
currentLayout = (LinearLayout.LayoutParams) currentView.getLayoutParams();
currentLayout.setMargins(currentLayout.leftMargin, currentLayout.topMargin, currentLayout.rightMargin + width/2, currentLayout.bottomMargin);
mTabHost.getTabWidget().requestLayout();

Categories

Resources