2017-02-25 134 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); 
相關問題