2017-02-25 102 views
0

如何以编程方式将工具栏添加到LinearLayout。 我试过下面的代码,但它不工作。如何以编程方式将工具栏添加到LinearLayout

我的课程扩展了FragmentActivity。

Toolbar toolbar = new Toolbar(this); 
Toolbar.LayoutParams toolBarParams = new Toolbar.LayoutParams(
     Toolbar.LayoutParams.MATCH_PARENT, 
     R.attr.actionBarSize 
); 
toolbar.setLayoutParams(toolBarParams); 
toolbar.setBackgroundColor(Color.BLUE); 
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay); 
toolbar.setVisibility(View.VISIBLE); 
LinearLayout ll = (LinearLayout) findViewById(R.id.activity_search); 
ll.addView(toolbar); 
+0

'R.attr.actionBarSize'为一个属性的资源标识符。这不是实际的大小。你需要做一些事情,如[本文](http://stackoverflow.com/a/7913610)中所示。除此之外,它究竟如何不工作? –

+0

即使如果我将R.attr.actionbarSize更改为100,它也不会显示任何内容。 – Nikhil

+1

好吧,还有其他一些可能的问题:'Toolbar'正在进入'LinearLayout',所以它需要'LinearLayout.LayoutParams',而不是'Toolbar.LayoutParams'。确保LinearLayout具有您期望的正确方向。还要确保'LinearLayout'中的任何现有子View都没有填充它,并将'Toolbar'推到外面。如果你想在其他子View的前面插入'Toolbar',可以使用'addView(View,int)'方法将它添加到特定的索引处。 –

回答

0

下面代码修改后的工作:

 Toolbar toolbar = new Toolbar(this); 
     LinearLayout.LayoutParams toolBarParams = new LinearLayout.LayoutParams(
       Toolbar.LayoutParams.MATCH_PARENT, 
       150 
     ); 
     toolbar.setLayoutParams(toolBarParams); 
     toolbar.setBackgroundColor(Color.BLUE); 
     toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay); 
     toolbar.setVisibility(View.VISIBLE); 


     LinearLayout ll = (LinearLayout) findViewById(R.id.activity_search); 
     ll.addView(toolbar, 0); 
相关问题