简体   繁体   中英

Pragmatically set Button in Right Side in Android

I was Creating Button Programatically using Linear Layout. But I Can't Change Logout Button Alignment to Right Side.

在此处输入图片说明

Thanks in Advance...

My Code is

lView = new LinearLayout(Main2Activity.this);
                   // lView.setPadding(0,150,0,0);
                    lView.setBackgroundColor(Color.parseColor("#EDFCFC"));
                    lView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));

                    Button logout = new Button(Main2Activity.this);
                    logout.setText("Logout");
                    logout.setGravity(Gravity.CENTER);

                    logout.setBackgroundColor(Color.parseColor("#F53F37"));
                    lView.addView(logout);

The setGravity that you are using is for the text inside the button . In order to set the gravity of the entire button you need to work with the layoutParams . Please try the below code:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER; 
logout.setLayoutParams(params);

try this:

 RelativeLayout rl = new RelativeLayout(Main2Activity.this);
Button logout = new Button(Main2Activity.this);
logout.setText("Hello, World");

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams
        (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
logout.setBackgroundColor(Color.parseColor("#F53F37"));
rl.addView(logout, lp);

you can try in your xml file to put in the Button the code :

android:layout_marginLeft="how much dp you want"

or try :

android:layout_gravity="right"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM