I want to create vertical LinearLayout with couple of Button children, where each child has width of widest of them.
However depending on using MATCH_PARENT or WRAP_CONTENT for children width, I get either LinearLayout taking whole screen's width, or Buttons not filling LinearLayout. Screenshots below (fill/wrap):
Example Activity code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout mainView = new RelativeLayout(this);
mainView.setBackgroundColor(Colors.WHITE);
String[] buttonsNames = new String[] { "Short", "Looooooong", "Medium" };
View buttonsView = getButtonsView(buttonsNames);
mainView.addView(buttonsView, new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT));
setContentView(mainView);
}
private View getButtonsView(String[] buttonNames) {
LinearLayout buttonsView = new LinearLayout(this);
buttonsView.setOrientation(LinearLayout.VERTICAL);
buttonsView.setBackgroundColor(Colors.BLACK);
for (int i = 0; i < buttonNames.length; i++) {
Button button = new Button(this);
button.setText(buttonNames[i]);
///////////// HERE LAYS THE PROBLEM //////////
buttonsView.addView(button, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
//LinearLayout.LayoutParams.WRAP_CONTENT, // neither of them works
LinearLayout.LayoutParams.WRAP_CONTENT));
View redLineDivider = new View(this);
redLineDivider.setBackgroundColor(Colors.RED);
buttonsView.addView(redLineDivider, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, 2));
}
return buttonsView;
}
As you can see on second screenshot, red lines actually take whole width without stretching LinearLayout - it is because at least one view has set width.
Potential fix I have came up with is to find widest button (with longest text) and make it use WRAP_CONTENT, while all the rest use MATCH_PARENT, which gives me expected result:
Code:
buttonsView.addView(button, new LinearLayout.LayoutParams(
isLongestText(i) ? LinearLayout.LayoutParams.WRAP_CONTENT
: LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
It doesn't feel like elegant solution though - is there any intended mechanism for situation like this, that I am missing out?
Following is the trick:
Mention the width of the LinearLayout containing the buttons (buttonsView in your code) as WRAP_CONTENT.
Mention the width of each button as MATCH_PARENT
Your program should give you the expected result if you do not include the redLineDivider View. There seems to be some issue with setting the width of redLineDivider. As an alternative you can declare it as a LinearLayout to make your code work perfectly.
// View redLineDivider = new View(this);
// Instead declare it as a LinearLayout
LinearLayout redLineDivider = new LinearLayout(this);
Hope this will be useful.
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.
My question is simple,
How to set my buttons layout_gravity programmatically?
I found this on internet, but it simply throws me a Nullpointer exception:
Button MyButton = new Button(this);
LinearLayout.LayoutParams lllp=(LinearLayout.LayoutParams)MyButton.getLayoutParams();
lllp.gravity=Gravity.RIGHT;
MyButton.setLayoutParams(lllp);
MyLinearLayout.addView(MyButton);
Any solution?
Java
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
params.gravity = Gravity.TOP;
button.setLayoutParams(params);
Kotlin
val params = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
weight = 1.0f
gravity = Gravity.TOP
}
For gravity values and how to set gravity check Gravity.
Basically, you should choose the LayoutParams depending on the parent. It can be RelativeLayout, LinearLayout etc...
I'd hate to be resurrecting old threads but this is a problem that is not answered correctly and moreover I've ran into this problem myself.
Here's the long bit, if you're only interested in the answer please scroll all the way down to the code:
android:gravity and android:layout_gravity works differently. Here's an article I've read that helped me.
GIST of article: gravity affects view after height/width is assigned. So gravity centre will not affect a view that is done FILL_PARENT (think of it as auto margin). layout_gravity centre WILL affect view that is FILL_PARENT (think of it as auto pad).
Basically, android:layout_gravity CANNOT be access programmatically, only android:gravity.
In the OP's case and my case, the accepted answer does not place the button vertically centre.
To improve on Karthi's answer:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
button.setLayoutParams(params);
Link to LinearLayout.LayoutParams.
android:layout_gravity shows "No related methods" meaning cannot be access programatically.
Whereas gravity is a field in the class.
I had a similar problem with programmatically setting layout_gravity on buttons in a GridLayout.
The trick was to set gravity on the button layoutParams AFTER the button was added to a parent (GridLayout), otherwise the gravity would be ignored.
grid.addView(button)
((GridLayout.LayoutParams)button.getLayoutParams()).setGravity(int)
MyButton.setGravity(Gravity.RIGHT);
For layout_gravity use the answer stated by "karthi". This method sets gravity to place the children inside the view.
layoutParams2.gravity = Gravity.RIGHT|Gravity.BOTTOM;
use this to add mor than one gravity
If you want to change the layou_gravity of an existing view do this:
((FrameLayout.LayoutParams) view.getLayoutParams()).gravity = Gravity.BOTTOM;
Remember to use the right LayoutParams based on the Layout type your view is in. Ex:
LinearLayout.LayoutParams
KOTLIN setting more than one gravity on FrameLayout without changing size:
// assign more than one gravity,Using the operator "or"
var gravity = Gravity.RIGHT or Gravity.CENTER_VERTICAL
// update gravity
(pagerContainer.layoutParams as FrameLayout.LayoutParams).gravity = gravity
// refresh layout
pagerContainer.requestLayout()
This question is old but I just had the same problem and solved it like this
LayoutParams lay = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)
lay.gravity = Gravity.CENTER;
I use someting like that: (Xamarin and C# code)
LinearLayout linLayout= new LinearLayout(this);
linLayout.SetGravity(GravityFlags.Center);
TextView txtView= new TextView(this);
linLayout.AddView(txtView);
the SetGravity puts my textView in the center of the layout.
So SetGravity layout property refer to layout content
In case you need to set Gravity for a View use the following
Button b=new Button(Context);
b.setGravity(Gravity.CENTER);
For setting layout_gravity for the Button
use gravity field for the layoutparams as
LayoutParams lp=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp.gravity=Gravity.CENTER;
try this
hope this clears
thanks
If you want to put a view in the center of parent, you can do with following code..
public class myLayout extends LinearLayout {
public myLayout(Context context) {
super(context);
RelativeLayout vi = (RelativeLayout) ((LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.activity_main, null);
LinearLayout.LayoutParams cc = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
cc.gravity = Gravity.CENTER;
this.setGravity(Gravity.CENTER);
this.addView(vi);
}
}
these code section make LinearLayout put the first view elements in the center of parent.
So, we system don't consider the initial width and high to arrange view in the center .
I do the code section well.
The rest of the answers are right, I want to add more explaination. The layout_gravity is about how to position the view in parent view.
You must set gravity **after method parentView.addView() ** was called. We can see the code:
public void setLayoutParams(ViewGroup.LayoutParams params) {
if (params == null) {
throw new NullPointerException("Layout parameters cannot be null");
}
mLayoutParams = params;
resolveLayoutParams();
if (mParent instanceof ViewGroup) {
((ViewGroup) mParent).onSetLayoutParams(this, params);
}
requestLayout();
}
And the problem of null pointer is because it's not calling addView before getLayoutParams().
The annotation was already said "This method may return null if this View is not attached to a parent ViewGroup or {#link#setLayoutParams(android.view.ViewGroup.LayoutParams)} was not invoked successfully. When a View is attached to a parent ViewGroup, this method must not return null."
to RelativeLayout, try this code , it works for me:
yourLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
Perfectly Working!!! None of the above answer works for me. In Xml file setting gravity and setting layout_gravity is different. Check out the below code
// here messageLL is the linear layout in the xml file
// Before adding any view just remove all views
messageLL.removeAllViews();
// FrameLayout is the parent for LinearLayout
FrameLayout.LayoutParams params = new
FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER|Gravity.CENTER_VERTICAL;
messageLL.setLayoutParams(params);
messageText.setVisibility(View.GONE);
messageNoText.setVisibility(View.VISIBLE);
messageLL.addView(messageNoText);
Also check This,where you can find clear explanation about gravity and layout_gravity .
Most of above answer are right, so written a helper methods, so you can use it
directly in you project .
set layout_gravity programmtically
// gravity types : Gravity.BOTTOM, Gravity.START etc.
// view : can be any view example : button, textview, linearlayout, image etc.
// for single view
public static void setLayoutGravity(int gravity, View view){
((LinearLayout.LayoutParams) view.getLayoutParams()).gravity = gravity;
}
// for mulitple views
public static void setLayoutGravity(int gravity, View ...view){
for(View item : view)
((LinearLayout.LayoutParams) item.getLayoutParams()).gravity = gravity;
}
Modify the existing layout params and set layout params again
//Get the current layout params and update the Gravity
(iv.layoutParams as FrameLayout.LayoutParams).gravity = Gravity.START
//Set layout params again (this updates the view)
iv.layoutParams = layoutParams
I switched from LinearLayout.LayoutParams to RelativeLayout.LayoutParams to finally get the result I was desiring on a custom circleview I created.
But instead of gravity you use addRule
RelativeLayout.LayoutParams mCircleParams = new RelativeLayout.LayoutParams(circleheight,circleheight);
mCircleParams.addRule(RelativeLayout.CENTER_IN_PARENT);
int width=getResources().getDisplayMetrics().widthPixels;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams
(width, width);
params.gravity = Gravity.CENTER;
iv_main_text = new HTextView(getContext());
iv_main_text.setLayoutParams(params);
iv_main_text.setBackgroundColor(Color.BLUE);
iv_main_text.setTextSize(60);
iv_main_text.setGravity(Gravity.CENTER);
iv_main_text.setTextColor(Color.BLACK);
FloatingActionButton sendFab = new FloatingActionButton(this);
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(32, 32, 32, 32);
layoutParams.gravity = Gravity.END|Gravity.BOTTOM;
sendFab.setLayoutParams(layoutParams);
sendFab.setImageResource(android.R.drawable.ic_menu_send);
Try this code
Button btn = new Button(YourActivity.this);
btn.setGravity(Gravity.CENTER | Gravity.TOP);
btn.setText("some text");
or
btn.setGravity(Gravity.TOP);
Can anyone help me how to set the width of TextView to wrap_content through code and not from XML?
I am dynamically creating a TextView in code ,so is there anyway to how to set its width to wrap_content through code?
TextView pf = new TextView(context);
pf.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
For different layouts like ConstraintLayout and others, they have their own LayoutParams, like so:
pf.setLayoutParams(new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
or
parentView.addView(pf, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
There is another way to achieve same result. In case you need to set only one parameter, for example 'height':
TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);
Solution for change TextView width to wrap content.
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.requestLayout();
// Call requestLayout() for redraw your TextView when your TextView is already drawn (laid out) (eg: you update TextView width when click a Button).
// If your TextView is drawing you may not need requestLayout() (eg: you change TextView width inside onCreate()). However if you call it, it still working well => for easy: always use requestLayout()
// Another useful example
// textView.getLayoutParams().width = 200; // For change `TextView` width to 200 pixel
A little update on this post: if you are using ktx within your Android project, there is a little helper method that makes updating LayoutParams a lot easier.
If you want to update e.g. only the width you can do that with the following line in Kotlin.
tv.updateLayoutParams { width = WRAP_CONTENT }
I am posting android Java base multi line edittext.
EditText editText = findViewById(R.id.editText);/* edittext access */
ViewGroup.LayoutParams params = editText.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
editText.setLayoutParams(params); /* Gives as much height for multi line*/
editText.setSingleLine(false); /* Makes it Multi line */
I think this code answer your question
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
holder.desc1.getLayoutParams();
params.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
holder.desc1.setLayoutParams(params);
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)