I am trying to add a button programmatically in a custom view implementation. App is API 15+.
Here I am facing issue with button text not getting centered. It sounds trivial, but it is not working. Below is code in question. output is
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mSubmit = new Button(mContext);
mSubmit.setTextColor(Color.WHITE);
mSubmit.setText("Submit");
mSubmit.setTextSize(getResources().getDimension(R.dimen.headertxt));
addView(mSubmit, params);
Set equal padding for all sides of your button:
for example:
myButton.setPadding(2,2,2,2);
Before:
After adding our padding:
addContentView worked for me!
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mSubmit = new Button(mContext);
mSubmit.setTextColor(Color.WHITE);
mSubmit.setText("Submit");
mSubmit.setTextSize(getResources().getDimension(R.dimen.headertxt));
addContentView(mSubmit, params);
It's not centered vertically, so try
mSubmit.setGravity(Gravity.CENTER_VERTICAL);
Could also be some custom background for the button that's not correctly set up -- it's not very clear from the image.
And note : The gravity you set on the layout params is a completely different thing than the gravity you set on the button.
I am currently doing an android application that contains customize alert dialog. It contains a button , but i can't set the margin for the button . the code is given below. setmargin method is not working
AlertDialog.Builder myDialog = new AlertDialog.Builder(Login.this);
Button button = new Button(Login.this);
button.setText("Send");
LayoutParams buttonLayoutParams
= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
button.setLayoutParams(buttonLayoutParams);
resetPassword=editText.getText().toString();
LinearLayout layout = new LinearLayout(Login.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(textView);
layout.addView(editText);
layout.addView(button);
myDialog.setView(layout);
Write below code to set margin, it may help you.
AlertDialog.Builder myDialog = new AlertDialog.Builder(Login.this);
Button button = new Button(Login.this);
EditText editText = new EditText(Login.this);
TextView textView = new TextView(Login.this);
button.setText("Send");
LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(50, 10, 0, 0);
button.setLayoutParams(buttonLayoutParams);
String resetPassword = editText.getText().toString();
LinearLayout layout = new LinearLayout(Login.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(textView);
layout.addView(editText);
layout.addView(button);
myDialog.setView(layout);
myDialog.show();
Use LinearLayout.LayoutParams or RelativeLayout.LayoutParams according to parent layout of the child view
Just sharing a slightly different approach.
Instead of casting to LinearLayout.LayoutParams, RelativeLayout.LayoutParams, etc, you can just cast to MarginLayoutParams.
Casting to MarginLayoutParams is better because you can later update your layout and you don't need to return to your java code to change from LinearLayout to RelativeLayout or any other Layout type
You can do something like:
MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
// Set bottom margin
layoutParams.bottomMargin = x;
// Set top margin
layoutParams.topMargin = x;
// Set left margin
// This won't have effect if you set any relative margin (start) previously or in the layout.xml
layoutParams.leftMargin = x;
// Set left margin
// This won't have effect if you set any relative margin (end) previously or in the layout.xml
layoutParams.rightMargin = x;
// Set start margin
layoutParams.setMarginStart(x);
// Set end margin
layoutParams.setMarginStart(x);
// Set all left, top, right, bottom margins at once
// Note that here, left and right margins are set (not start/end).
// So, if you have used start/end margin before (or via layout.xml),
// setting left/right here won't have any effect.
layoutParams.setMargins(left, top, end, bottom)
// Then re-apply the layout params again to force the view to be re-draw
// This step may not be necessary because depending where you set the margin,
// view is already scheduled to be drawn
// For any case, to ensure the view will apply the new margin, call:
view.setLayoutParams(layoutParams);
buttonLayoutParams.bottomMargin
buttonLayoutParams.topMargin
buttonLayoutParams.leftMargin
buttonLayoutParams.rightMargin
can be used to set margins
The setMargin() method is available if you're using LinearLayout.LayoutParams but not if you're using ViewGroup.LayoutParams. Dipak Keshariya alludes to this but doesn't say it in so many words.
You can set in LinearLayout margin
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);
This works for me (The support library (need to use AndroidX):
Kotlin
val params = LinearLayoutCompat.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
).apply {
setMargins(0,16,0,16)
}
Java
LinearLayoutCompat.LayoutParams params = LinearLayoutCompat.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
params.setMargins(0,16,0,16)
I have this code:
ImageButton call = new ImageButton(context);
call.setId(9001+result.index);
call.setBackgroundResource(R.drawable.small_call);
LinearLayout.LayoutParams call_params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
call.setLayoutParams(call_params);
It renders the button the way I want it, but when I do this:
ImageButton call = new ImageButton(context);
call.setId(9001+result.index);
call.setBackgroundResource(R.drawable.small_call);
LinearLayout.LayoutParams call_params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT,
Gravity.CENTER_VERTICAL | Gravity.RIGHT
);
call.setLayoutParams(call_params);
It stretches the image, messing up the aspect ratio, and makes it blurry/pixelated.
So what is the correct way to render the image as in the first code snippet, but place the button where the second code snippet puts it?
Thanks in advance.
Use RelativeLayout or FrameLayout instead of LinearLayout.
See also layout_gravity in LinearLayout.
This is a tutorial: A Visual Guide to Relative Layouts In Android.
I' m at this point stuck : I want to have a scrollview + a fixed button at the bottom, but Programatically Way ! I can' t go with XML for some technical reason.
Actually i have this :
//Is it really usefull Relative View?
RelativeLayout layout = new RelativeLayout(this);
ScrollView sv = new ScrollView(this);
sv.setId(2);
// What is it? RelativeLayout.LayoutParams?
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, sv.getId());
sv.setLayoutParams(new ViewGroup.LayoutParams(480, 800));
layout.addView(saveButton, lp);
layout.addView(sv);
I do the first 3 page Google on "fixed button and scrollview Android programatically"
Im beginner on Android, so, don' t hesitate to comment on my code some hints ;)
Thx for your help.
try this
LinearLayout layout = new LinearLayout(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(lp);
ScrollView scroll = new ScrollView(this);
LinearLayout.LayoutParams slp = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,0, 1.0f);
scroll.setLayoutParams(slp);
Button btn = new Button(this);
ViewGroup.LayoutParams blp = new ViewGroup.LayoutParams(
LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
btn.setLayoutParams(blp);
btn.setText("Click Me");
layout.addView(scroll);
layout.addView(btn);
setContentView(layout);
If you are trying to create a view where the upper portion of the screen is a scrolling list, and the bottom portion is a button, put the scrollview inside a linearlayout, and put the button in the linearlayout below the scrollview.
http://developer.android.com/reference/android/widget/LinearLayout.html
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);