java - Android Adding Buttons to Toolbar Programmatically


Question: 

I am trying to create a toolbar programmatically and Add Left and Right Bar Button to it without using XML.

But the button is not getting aligned to right. So kindly help me.

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




2 Answers: 

In Activity code

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar t=(Toolbar)findViewById(R.id.tool);
    setSupportActionBar(t);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

    //left side button

    Button b=new Button(this);
    Toolbar.LayoutParams l1=new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
    l1.gravity=Gravity.START;
    b.setLayoutParams(l1);
    b.setText("left");
    t.addView(b);

    //center Textview
    TextView text=new TextView(this);
    text.setText("Text:1");
    Toolbar.LayoutParams l2=new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
    l2.gravity=Gravity.CENTER;
    text.setLayoutParams(l2);
    t.addView(text);

    //Right side button

    Button b1=new Button(this);
    b1.setText("Right");
    Toolbar.LayoutParams l3=new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
    l3.gravity=Gravity.END;
    b.setLayoutParams(l3);
    t.addView(b1);

}

Toolbar XML code

<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:background="@color/colorAccent"
android:id="@+id/tool"
app:contentInsetLeft="0dp"
android:paddingRight="10dp"
android:paddingLeft="10dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"
android:layout_height="wrap_content">

</android.support.v7.widget.Toolbar>

OUTPUT enter image description here

 

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

 

More Articles


android - hide toolbar when collapsing collapsingtoobarlayout

What I am trying to achieve is hide the collapsingtoolbarlayout when scrolling my recyclerview and collapse the maintoolbar if scrolled further. but I can achieve only upto this http://i.imgur.com/t6wTW5H.gif.<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="htt

javascript - get a smooth animation for a canvas game

How to get a better animation, dinamically, even when browser is busy or idle, for different devices which have different hardware capacity.I have tried many ways and still cannot find the right way to make the game to display a better animation.This is what i tried:var now;var then = Date.now();var

android - How to create bottomsheet with toolbar when expanded,

I want to create bottom sheet layout, which when expanded to full screen should display toolbar. I have used following code but it is displaying toolbar even if its not expanded to full screen.<?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:an


python - Mayavi: Customize toolbar

Is there a way to customize the default toolbar of a mayavi scene? I would like to delete some buttons as I don't need them (e.g. the save button). Here you can see which toolbar I am talking about:The code is just an example code:import osos.environ['ETS_TOOLKIT'] = 'qt4'from pyface.qt import QtGui

Keras error when finetuning InceptionV3

I am trying to follow the "Fine-tune InceptionV3 on a new set of classes" sample code to freeze the first 172 layers and re-train the last layers on cats/dogs dataset. I keep getting an error which I have noted at the bottom. Please help. I am using Ubuntu 16.04, keras 1.2.1, theano 0.9.0beta1.dev,

xamarin.android - How to align UI controls on a Custom Toolbar in Android xml

I'm creating a layout in Xamarin.Android and I'm working on a custom Toolbar with an image button a TextView and another label. What I need to do is Make sure the imagebutton BackButton is left aligned all the way to the left of the parent Contain, the TextView is Center Aligned and the MenuButton


c++ - Windows Toolbar - Controlling button size and padding

I'm trying to understand the behaviour of a Windows toolbar - in particular how the following values interact:the size of the bitmap image usedthe effective size of a toolbar buttonthe padding between the image and the button edgethe height of the toolbarText displayed by a button is not relevant in

compact framework - Toolbar button sizes in windows mobile 6.5.3

We have a VB.net CF2.0 Apllication that up until now has run on windows mobile platforms from 2003 to 6.0 without any major issues. Our current team use HP iPAQ devices running winodws 6.0 and everything runs fine. There is a good, hardware related reson why we use these devices. We are looking to u

wpf - Giving a stackPanel the same LinearGradientBrush as the toolbar has by default

I have two ToolBars side by side (I had to do that so I could align buttons right and left)But now, I have to add some text that can be aligned right left or center between both toolbars. I added the text in a TextBlock inside a StackPanel disposed on a Grid at the second position (between the toolb

formatting - Excel 2007 floating format toolbar customisation

Is it possible in Excel 2007 to customise the floating format bar that is shown when you right-click on a cell? To avoid confusion, I don't mean the "Cell" commandbar menu, but the second floating toolbar with formatting buttons.e.g. is it possible to add a Styles dropdown, or have any other text al