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.
Related
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)
I tried to use below code, but the textviews do not change line after it reach the end of screen.
RelativeLayout ll = (RelativeLayout)findViewById(R.id.viewObj);
int lastid=0;
for (int i=0; i<100; i++) {
String teststr = " hello ";
TextView textView2 = new TextView(this);
textView2.setId(i+1);
textView2.setTextSize(30);
textView2.setBackgroundColor(Color.GREEN);
textView2.setTextColor(Color.RED);
textView2.setTypeface(Typeface.MONOSPACE);
textView2.setText(teststr+String.valueOf(i));
if (i>0)
{
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lay.addRule(RelativeLayout.RIGHT_OF, lastid);
ll.addView(textView2, lay);
} else {
ll.addView(textView2);
};
lastid = textView2.getId();
}
However, I dont know how to determine when to change line. I just keep on putting new textview to the right of the last one created. Can anyone tell me the correct logic to do the task? many thanks.
Easy fix. Switch to a dynamically-created LinearLayout, and set its orientation to vertical:
lay.setOrientation(LinearLayout.VERTICAL);
I'm trying to display a bunch of text on the screen by placing TextViews inside rows of single-line LinearLayouts. Each word is stored in its own separate TextView, and I want to be able to place as many TextViews as will fit on a single LinearLayout line and detect when I've run out of horizontal space so that I can move to the next line.
The problem I'm facing is that I can't seem to find a way to measure the changing layout sizes as I create the display, because I can't get a reference width using getWidth() on the parent layout, and even after I add the TextViews, I can't seem to control the width.
We had a working version before, but it did everything using on hard-coded numbers based on the number of characters in a TextView at a fixed size. I'm trying to extend the app to work with all text and screen sizes. If this needs to be completely overhauled, I understand - I just want to be able to fill up the screen with an indefinite number of lines of text.
An obvious solution would be to just place all the text inside one TextView, but we need to be able to access each Word/Ponctuation object and its attributes through the displayed TextViews.
// layout_row is the current LinearLayout row I'm adding my TextViews to
// layout is the LinearLayout parent of all layout_rows
// text.text_content is a linked list of Word and Ponctuation objects
// each Word and Ponctuation object has a TextView attribute called view
private void display_views() {
if (text != null)
{
boolean prochainLigneSuivante; // if new line is to follow
int widthSoFar = 0;
int layoutWidth = layout_row.getWidth();
for (Object o : text.text_content) {
if (o instanceof Word ) {
Word w = (Word) o;
Object next = text.next(o);
if (noNeedForSpace(w)) {
// by default all TextViews have
// right padding to simulate spaces
w.view.setPadding(0, 0, 0, 0);
}
layout_row.addView(w.view);
widthSoFar += w.view.getWidth();
// Am I out of space?
prochainLigneSuivante = widthSoFar >= layoutWidth;
if(prochainLigneSuivante) {
layout_row.removeView(w.view);
widthSoFar = 0;
layout_row = new LinearLayout(context);
layout_row.setOrientation(LinearLayout.HORIZONTAL);
layout_row.addView(w.view);
layout_row.setBackgroundColor(Color.BLACK);
layout_row.setLayoutParams(new
LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT));
layout.addView(layout_row);
}
}
else if (o instanceof Ponctuation) {
Ponctuation p = (Ponctuation) o;
if (p.text.contains("CR")) {
layout_row = new LinearLayout(context);
layout_row.setOrientation(LinearLayout.HORIZONTAL);
layout_row.setLayoutParams(new
LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.MATCH_PARENT));
widthSoFar = 0;
layout.addView(layout_row);
}
else {
if (p.view.getText().equals(" "))
p.view.setPadding(0, 0, 0, 0);
layout_row.addView(p.view);
if(!p.view.getText().equals(""))
widthSoFar += p.view.getWidth();
}
}
}
}
else {
Log.e("Text", "text est nul");
}
scroll.refreshDrawableState();
transition.startTransition(0);
}
I'm creating a button dynamically. The number of button is depend on the size of arraylist. the problem is, after creating the button I will add to the layout using addview method. The problem is I'm using linear layout, as by default orientation for linear layout is horizontal, so the button will fill the layout horizontally. Because of that some of the button is not visible. What I'm trying to achieve is something look like this
My code is like below:
Button[] tv = new Button[arraylist.size()];
for(int i=0;i<arraylist.size();i++){
tv[i] = new Button(getApplicationContext());
tv[i].setText(arraylist.get(i).toString());
tv[i].setTextColor(Color.parseColor("#000000"));
tv[i].setTextSize(20);
tv[i].setPadding(15, 5, 15, 5);
linearlayout.addView(tv[i]);
}
If I set the orientation of linear layout to vertical the button will fill vertically. So if there any solution to create the button dynamically and fill the layout both horizontal and vertical as shown by image.
There is not a canned layout in the SDK that does exactly what you are aiming for (i.e. lay out as many children horizontally as will fit, then flow to the next line to lay out some more), so you will need to create a custom ViewGroup that accomplishes this purpose. Luckily for you, Romain Guy created one live on-screen during a presentation at Devoxx.
Here is a link to that presentation video.
Here is a link to the sample code and slides.
HTH
After 2 days struggling thinking bout this problem finally I've found the solution. I've try put all my contact list, store it in arraylist and create button for each element and I'm quite satisfy with the result after display on the screen. Here is how I do the trick. I really appreciate for any comment from others.
variable declaration;
int currWidth;
int currCounter;
boolean isNewLine;
LinkedList<HashMap<String,Object>> button;
ArrayList<String> nameNumber = new ArrayList<String>();
contactWrapper = (LinearLayout) findViewById(R.id.multiple_selection);
create button onClick event;
for(int i=0;i<nameNumber.size();i++){
tv[i] = new Button(getApplicationContext());
String[] namePhone = nameNumber.get(i).toString().split("##");
phoneNumber.add(namePhone[1]);
tv[i].setText(namePhone[0]);
tv[i].setTag(namePhone[1]);
tv[i].setTextColor(Color.parseColor("#000000"));
tv[i].setTextSize(20);
tv[i].setPadding(15, 5, 15, 5);
tv[i].measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
HashMap<String, Object> map = new HashMap<String,Object>();
map.put("button", tv[i]);
map.put("width", tv[i].getMeasuredWidth());
button.add(map);
}
drawLayout();
drawlayout method is where I add button and arrange accordingly to fit the layout;
public void drawLayout(){
int counter=0;
contactWrapper.setOrientation(LinearLayout.VERTICAL);
currCounter=0;
currWidth=0;
isNewLine=false;
LinearLayout[] row = new LinearLayout[nameNumber.size()];
row[currCounter] = new LinearLayout(getApplicationContext());
#SuppressWarnings("rawtypes")
Iterator it = button.iterator();
for(int i = 0; i<button.size(); i++){
it.next();
row[currCounter].setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT));
currWidth += Integer.parseInt(button.get(i).get("width").toString());
if(isNewLine){
if(currWidth < contactWrapper.getWidth()){
row[currCounter].addView((View) button.get(i).get("button"));
if(!it.hasNext()){
contactWrapper.addView(row[currCounter]);
}else{
if(contactWrapper.getWidth()<(currWidth+Integer.parseInt(button.get(i+1).get("width").toString()))){
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}else{
isNewLine=false;
}
}
}else{
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}
}else{
if(currWidth < contactWrapper.getWidth()){
if(!it.hasNext()){
row[currCounter].addView((View) button.get(i).get("button"));
contactWrapper.addView(row[currCounter]);
}else{
row[currCounter].addView((View) button.get(i).get("button"));
if(contactWrapper.getWidth()<(currWidth+Integer.parseInt(button.get(i+1).get("width").toString()))){
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}else{
isNewLine=false;
}
}
}else{
isNewLine=true;
contactWrapper.addView(row[currCounter]);
currCounter+=1;
row[currCounter] = new LinearLayout(getApplicationContext());
currWidth=0;
}
}
counter++;
}
}
this code quite messy + I'm not fully utilize the size of array for
LinearLayout[] row = new LinearLayout[nameNumber.size()];
but it work for me.
use TableLayout instead of LinearLayout this is tutorial hope this will help you to get the idea
Does you set android:layout_width="fill_parent"?
Do this if you don't.
Well, you can try using more sophisticated way. You can create horizontal linear layout, and add buttons to it. Every time you're attempting to add new button, you check if there is place for it, by finding difference between layout's and buttons widths.
Each time your horizontal layout is filled, you add it to another vertical layout, and create another horizontal layout to store buttons left.
I used that trick in my apps.
try this its working fine
this.row = (LinearLayout)findViewById(R.id.tags);
this.row.setOrientation(LinearLayout.VERTICAL);
LinearLayout one = new LinearLayout(this);
//get the size of the screen
Display display = getWindowManager().getDefaultDisplay();
this.screenWidth = display.getWidth(); // deprecated
this.screenHeight = display.getHeight();// depreceted
for(int i=0; i<6; i++) {
one.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
this.button = new Button(this);
button.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
if(i==0) {
this.button.setText("Muhammad Aamir");
} else if(i==1) {
this.button.setText("Ahsan");
} else if(i==2) {
this.button.setText("Mujahid");
} else if(i==3) {
this.button.setText("Waqas");
} else if(i==4) {
this.button.setText("Ali");
} else {
this.button.setText("Ahmer");
}
//get the size of the button text
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(button.getTextSize());
mPaint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.NORMAL));
float size = mPaint.measureText(button.getText().toString(), 0, button.getText().toString().length());
size = size+14;
this.totalTextWidth += size;
if(totalTextWidth < screenWidth) {
one.addView(button);
} else {
this.row.addView(one);
one = new LinearLayout(this);
one.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
one.addView(button);
this.totalTextWidth = size;
}
}
this.row.addView(one);
}
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.