2017-05-27 134 views
2

我正在尝试以编程方式创建工具栏,并在不使用XML的情况下向其添加左和右栏按钮。Android将按钮以编程方式添加到工具栏

但是按钮没有正确对齐。 所以请帮助我。

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); 

也试过

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

我得到如下图像

enter image description here

但需要像

enter image description here

+0

你能添加一些截图为更好地理解 – jagapathi

+0

新增截图... –

回答

3

在活动代码

@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); 

} 

工具栏的XML代码

<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> 

输出 enter image description here

+0

灿你修改,所以我们建立工具栏一个也可以使用Java代码而不是XML。 我不想要XML中的任何内容,因为我想重复使用此代码。 –

+1

好的我会尝试@SujayUN – jagapathi

+0

也考虑投票我的问题 –

相关问题