Android Adding Buttons to Toolbar Programmatically

Viewed 11342

I am trying to create a toolbar programmatically and add left and right bar buttons without using XML.

But the button is not getting aligned to right.

Toolbar TopTulBarVar = new Toolbar(this);
TopTulBarVar.setId(View.generateViewId());
TopTulBarVar.setBackgroundColor(Color.parseColor("#DDDDDD"));
TopTulBarVar.setTitle("Ttl Txt");
TopTulBarVar.setSubtitle("Dtl Txt");

Button NamBarBtnVar = new Button(this);
NamBarBtnVar.setText("Select");
NamBarBtnVar.setBackgroundColor(Color.GREEN);
LinearLayout.LayoutParams NamBarBtnRulVar = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
NamBarBtnRulVar.gravity = Gravity.RIGHT;
TopTulBarVar.addView(NamBarBtnVar, NamBarBtnRulVar);

Also tried

RelativeLayout.LayoutParams RloRulVar = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    RloRulVar.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

I am getting as below image

enter image description here

But need like

enter image description here

3 Answers

For anyone struggling with this nowadays: please make sure to use androidx.appcompat.widget.Toolbar.LayoutParams while adding view programmatically as for me just typing Toolbar.LayoutParams were accidentally resolved to android.widget.Toolbar.LayoutParams by Android Studio. I spent some time trying to figure out why gravity is not changed: no exception occures if set wrond layoutParams before adding a view to the toolbar. I have androidx.appcompat.widget.Toolbar in my layout.

for me I added one switch button in Toolbar and it does work :

            <Toolbar
                    android:id="@+id/toolbar"
                    style="@style/Toolbar"
                    android:visibility="visible"
                    android:background="@color/white">

                <Switch
                        android:id="@+id/btn_accessible"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_margin="10dp"
                        android:layout_weight="1"
                        android:visibility="visible"
                        android:paddingLeft="25sp"
                        android:paddingRight="25sp"
                        android:layout_centerHorizontal="true"
                        android:layout_centerVertical="true"
                        android:text=""
                        android:textColor="@color/white"
                        android:textSize="12sp"
                        android:thumb="@drawable/custom_switch_thumb"
                        android:track="@drawable/custom_switch_track"

                />


            </Toolbar>

and in activity i just set onClick listener

Related