Adding margins to button object programatically - android

Need to set left margin to a button object programatically.
This is the code segment:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.for_button);
MarginLayoutParams ml = new MarginLayoutParams(-2,-2);
ml.setMargins(5, 0, 0, 0);
Button btn = new Button(this);
btn.setText("7");
btn.setTextColor(Color.WHITE);
btn.setBackgroundResource(R.drawable.date_button);
rl.addView(btn,ml)
I also tried
btn.setLayoutParams(ml);
rl.addView(btn);
Whats the big problem. Or is there any alternative way?

Alright, I'm gonna give this a shot IronBlossom; this is how I do it and I hope it works:
LinearLayout myLinearLayout = (LinearLayout)findViewById(R.id.my_linear_layout);
Button myButton = new Button(this);
// more myButton attribute setting here like text etc //
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
params.setMargins(5,0,0,0);
myLinearLayout.addView(myButton, params);
best,
-serkan

You use a RelativeLayout as the parent for the button, but you don't specify any rules for the it where to place the button (e.g. ALIGN_PARENT_LEFT and ALIGN_PARENT_TOP).
You have to set rules for position when using a RelativeLayout though, so this messes with the layout calculation. This means that you have to use RelativeLayout.LayoutParams instead of the MarginLayoutParams because the former allows these rules and has proper default values set.
Alter this line:
MarginLayoutParams ml = new MarginLayoutParams(-2,-2);
to
RelativeLayout.LayoutParams ml = new RelativeLayout.LayoutParams(-2,-2);
Chances are that you also want to add rules because the default positioning values don't suit you (views get positioned in the top left corner of the parent layout by default). You can use RelativeLayout.LayoutParams.addRule() for that.

Related

Add UI elements dynamically in android

I want to add some ui elements to my android app, a Button for example!
But I can't find a complete tutorial! I found this code after a lot of searches:
LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
Button btn = new Button(this);
btn.setText("Manual Add");
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(btn);
My first problem is first line! Can you explain it for me please? What is R.id.layout? I know R is an object for resources but I don't know what is layout!
Second problem is line 3, What is LayoutParams?
Thank you all!
You can create views using default constructors for example
Button button = new Button(context);
After that you should determine to which type of parent view you are going to attach it, and create corresponding layot params. Every parent view LayoutParams type has uniqe customize methods, for example rules of RelativeLayout.LayoutParams.
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height)
//customize params here
button.setLayoutParams(params)
Attach view to your parent view
frameLayout.addView(button)
That is it.
LinearLayout ll = (LinearLayout)findViewById(R.id.layout);// you are getting a refrence to your layout
Button btn = new Button(this); // creating a new object of button type
btn.setText("Manual Add"); //setting the button text
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT)); //setting the width and height of the element
ll.addView(btn);//adding the button to your layout
R.id.layout is the name of your activity layout
It is the parent view which you are going to add your views. In your example it is a LinearLayout called layout.

Android: Align a Button to the Right in LinearLayout

I have a piece of code which I use to create a new LinearLayout. Within the layout I wish to add a TextView which contains both a label and a value. Then next to it on the right I want to display the button. I want the button to be located toward the end of the screen, without stretching the button. I am happy with the button width and height as WARP_CONTENT.
How can I achieve this in code? I have barely any XML so using XML is not an option. I am trying to make the app as dynamic as possible, so I decided to steer clear of XML.
Please see the code below:
// Build a button
final Button addButton = new Button(task.getParent());
addButton.setText("Add New");
addButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Open a file picker here to let the user pick a file
}
});
// Build a new layout to hold all the elements
LinearLayout verticalLayout = new LinearLayout(task.getParent());
verticalLayout.setOrientation(LinearLayout.HORIZONTAL);
verticalLayout.addView(sizeTextView);
verticalLayout.addView(addButton);
Thank you guys in advance.
Try this: Add Space (View) between TextView & Button.
// View space = new View(parent_context);
View space = new View(task.getParent());
// Width:0dp, Height:1 & Weight: 1.0
LinearLayout.LayoutParams spaceLP = new LinearLayout.LayoutParams(0, 1, 1.0f);
space.setLayoutParams(spaceLP);
verticalLayout.addView(sizeTextView);
verticalLayout.addView(space);
verticalLayout.addView(addButton);
Add textview with size and gravity,like this:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
params.setLayoutDirection(Gravity.RIGHT|Gravity.CENTER_VERTICAL);
verticalLayout.addView(sizeTextView,params);
To achieve this you should use Relative layout and RelativeLayout.LayoutParams. By using LayoutParams you can set the rule to align your views as per your requirements.
for example
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);
button.setLayoutParams(params);

how to change the width of a button dynamically

I have a method that creates several buttons
public Button[] generaBottoniRisposta(int numeroBottoni, Context context){
Button bottoni[]= new Button[numeroBottoni];
/*genero un tot di bottoni in base a numeroBottoni, รจ necessario avere il context*/
for(int i=0; i < bottoni.length;i++){
bottoni[i] = new Button(context);
bottoni[i].setId(i);
bottoni[i].setText(String.valueOf(i+1));
LayoutParams param = new LinearLayout.LayoutParams(50, 50);
bottoni[i].setLayoutParams(param);
}
return bottoni;
}
and then another method that add them to a gridlayout.
I want to set the width of those buttons, but i'm not able to do it.
I tried a lot of stuff, setWidth(), setMaxWidth(), invalidate() etc.
Something weird happens. If I try to make the button bigger than its default size it works, if i try to make the button smaller than its default size it doesn't work!
How should I do? thank you
Try using LayoutParams, something like..
RelativeLayout.LayoutParams rel_bottone = new RelativeLayout.LayoutParams(buttonWidth, buttonHeight);
button.setLayoutParams(rel_bottone);
And the layout depends on the parent layout that contains the buttons..
I think setlayoutparams should do what you want. Like in the answer in this thread.
Set View Width Programmatically
try this:
LinearLayout.LayoutParams params = button.getLayoutParams();
params.width = 100;
button.setLayoutParams(params);
one more thing LinearLayout.LayoutParams is used when parent is a LinearLayout and when parent is RelativeLayout use RelativeLayout.LayoutParams.
Try something like this :
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height);
button.setLayoutParams(params);
My buttons are inside a gridlayout. I tried to use GridLayout.LayoutParams giving the width of the cells, instead of trying to set the width of the button, and now it seems to work.
this is the code I use to add the buttons to the GridLayout
Spec row = GridLayout.spec(numeroRiga, 1);
Spec colspan = GridLayout.spec(numeroColonna, 1);
GridLayout.LayoutParams gridLayoutParam = new GridLayout.LayoutParams(row,colspan);
gridLayoutParam.width=50;
gridLayoutParam.height=50;
gridLayout.addView(button,gridLayoutParam);
But i'm wondering if i can set the width of the buttons in a similar way.

How to align image in android

I am dynamically adding controls in my activity. simultaneously i'm adding a editbox and button, but facing some issue in image alignment.
Here is my code which ads the editText and Button and returns to the linear layout which is vertical in alignment.
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(0);
final EditText textView = new EditText(this);
textView.setLayoutParams(lparams);
textView.setSingleLine(true);
final LayoutParams lparams1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
textView.setLayoutParams(lparams1);
if(id == R.id.new_alternate_number_button)
{
if(contactNumber == "")
{
textView.setHint("Enter contact Number");
}
else
{
textView.setText(contactNumber);
}
textView.setInputType(InputType.TYPE_CLASS_PHONE); //to popup numpad
}
else
{
if(contactEmailID == "")
{
textView.setHint("Enter Email ID ");
}
else
{
textView.setText(contactEmailID);
}
}
button.setBackgroundResource(R.drawable.ic_delete);
button.setBackgroundResource(R.drawable.ic_delete);
button.setOnClickListener(deleteView);
layout.addView(textView);
layout.addView(button);
textView.post(new Runnable() {
public void run() {
textView.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(textView, InputMethodManager.SHOW_IMPLICIT);
}
});
return layout;
In my XML file i have declared linear layout which is vertical in alignment i.e icon should be at the end of screen and EditText should be left aligned.. also i need a space between EditText and image..
Thanks in advance
Your LayoutParams is set to WRAP_CONTENT for Width instead of FILL_PARENT (or MATCH_PARENT).
A "pattern" that I use in similar cases is that even though I'm dynamically adding a new row/section, I still keep they layout in an xml file for that row, and then I dynamically inflate and find the elements by id, and bind to them. Sort of like how we deal with List Items except in this case, you are not using a list.
By keeping the layout in the XML file, it'll be easier to prototype what you want to see, add padding etc. And you can even use a RelativeLayout if you can't get the LinearLayout to work. Again, you can do all of this in code, but doing layout in the XML offers more flexibility (and is simpler to deal with in my mind)
This how you can go about adding space between the Button and EditText:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(50, 0, 0, 0); // Adding margin to the left of your button
Button yourButton = new Button(this);
yourButton.setText("some text");
linearLayout.addView(yourButton, layoutParams);
The sequence of parameters in setMargins method:
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom
Know more about setMargins method here.
Now that I realize your requirements properly (at least I guess so) I have another answer for you. Keep me updated about how it helps.
You will have to specify weight for the elements. Let's say total weightSum of your layout is 8, then if you specify weight of the EditText as 7, it will take 7/8th of the total space. And set wight of the Button as 1, so it will take 1/8th of the space. I am using 8 just as an example, you can change it to any number you want, do some trial and error see what weights are suiting your needs the best.
Also, the weights are in float, so don't forget the "f" after the number, like 1f and 7f:
(Again, I am not near my dev machine so there may be some errors. But this should work.)
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 7f);
// Last parameter 6f defines weight. So yourEditText will take 7/8th of the space
linearLayout.addView(yourEditText, layoutParams);
layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
// Last parameter 6f defines weight. So yourEditText will take 1/8th of the space
linearLayout.addView(yourButton, layoutParams);
Let's see how this helps. :)

How to align a dynamically create UserInterface using RelativeLayout in Android

I want to create a relative Layout dynamically through code with 2 Textviews one below the other.How to implement android:layout_below property through code in Android.
can anyone help me in sorting out this issue.
Thanks in Advance,
final TextView upperTxt = (...)
upperTxt.setId(12345);
final TextView lowerTxt = (...);
final RelativeLayout.LayoutParams params = RelativeLayout.LayoutParams(this, null);
params.addRule(RelativeLayout.BELOW, 12345);
lowerTxt.setLayoutParams(params);
Here is my solution for my special Problem.
In case the username wouldn't be found in the db i had to create a RelativeLayout that looks like the xml-generated one.
// text view appears on top of the edit text
enterNameRequest = new TextView(mainActivity.getApplicationContext());
// fill the view with a string from strings.xml
enterNameRequest.setText(mainActivity.getResources().getString(R.string.enterNameRequest));
// edit text appears below text view and above button
enterName = new EditText(mainActivity.getApplicationContext());
enterName.setId(667);
// button appears at the bottom of the relative layout
saveUserName = new Button(mainActivity.getApplicationContext());
saveUserName.setText(mainActivity.getResources().getString(R.string.useUserName));
saveUserName.setId(666);
// generate the relative layout
RelativeLayout layout = new RelativeLayout(mainActivity.getApplicationContext());
layout.setId(668);
// set a background graphic by its id
layout.setBackgroundDrawable(mainActivity.getApplicationContext().getResources().getDrawable(R.drawable.background_head_neutral));
// runtime told me that i MUST use width and height parameters!
LayoutParams params2 = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params2.addRule(RelativeLayout.ABOVE, 666);
enterName.setLayoutParams(params2);
LayoutParams params3 = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params3.addRule(RelativeLayout.ABOVE, 667);
enterNameRequest.setLayoutParams(params3);
LayoutParams params4 = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
params4.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 668);
saveUserName.setLayoutParams(params4);
// add views
layout.addView(enterNameRequest);
layout.addView(enterName);
layout.addView(saveUserName);
/* todo: set button action */
mainActivity.setContentView(layout);
What i found out additionally:
It is not so good to manipulate the layout manually from within java!
You should better use a new Activity and set a new layout in it.
This way, the application-code is readable a lot better!
I even tried to set several layouts (not manually, but wit setContentView) in one activity, and it turned out that i didn't know where what was accessing what else... Also, i had a great problem in adding onClickListeners... so you better use -- android:onClick="myButtonMethod" -- in your button tag in the xml and have a method in your according activity, which uses the layout, like this:
public void myButtonMethod(View v){
// do stuff
}
This improves performance because you are not using additional Listeners - but you use the already available Listener that is bound to your activity in every case.
u can try this
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)

Categories

Resources