[英]set Toolbar height programmatically Android
我試圖通過這種方式以編程方式設置工具欄的高度:
toolbar.setLayoutParams(new Toolbar.LayoutParams(LayoutParams.MATCH_PARENT, 42));
toolbar.setMinimumHeight(42);
但它導致這個日志致命異常 - > android.widget.relativelayout$layoutparams cannot be cast to android.support.v7.Toolbar$layoutparams
我也嘗試這個變種:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) toolbar.getLayoutParams();
params.height = 42;
toolbar.setLayoutParams(params);
toolbar.setMinimumHeight(42);
它沒有給出異常,但它也不起作用,工具欄得到它的默認更大的高度而不是我定義的。 但是當然在xml
設置參數是有效的,但我也需要在java中設置高度。
所以請幫我解決問題。
試試這個 -
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mToolbar.getLayoutParams();
layoutParams.height = 42;
mToolbar.setLayoutParams(layoutParams);
這對我來說可以。
如果上面的代碼仍然不起作用,請嘗試在最后添加此行 -
mToolbar.requestLayout();
以上行將強制您的工具欄重新測量所有內容。 您的代碼可能無法正常工作,因為您試圖在布局膨脹后更改高度。 在這種情況下,您需要強制View重新測量所有內容。 請查看以下方法以獲取更多信息 - requestLayout(),invalidate()和forceLayout()。 在改變LayoutParams的同時,這三種方法都很方便但價格很高。 如果您的布局非常繁重且包含大量子視圖,則調用這些方法中的任何一種都會影響應用程序的性能,特別是在低端設備上。 因此,請確保您仔細使用這些方法。
您提到的崩潰正在發生,因為您的工具欄是根視圖的子視圖,您的根視圖是RelativeLayout。 希望能幫助到你。
另外請不要按照Silambarasan Poonguti的回答,因為它有點含糊不清。 如果您嘗試訪問子LayoutParams,則需要進行LayoutParams轉換。 即使View有自己的LayoutParams,你必須將它轉換為父或根LayoutParams。 如果您的工具欄是RelativeLayout的子視圖,那么將LayoutParams轉換為Toolbar.LayoutParams會使應用程序崩潰,您必須將LayoutParams強制轉換為RelativeLayout.LayoutParams
試試這個...
工具欄有自己的LayoutParams 。 你不能把它投射到RelativeLayout。
Toolbar.LayoutParams params = (Toolbar.LayoutParams)mToolbar.getLayoutParams();
params.height = 42;
mToolbar.setLayoutParams(params);
如果要在運行時設置工具欄的高度,只需這樣做,
int expected_height = your value;
mToolbar.setMinimumHeight(expected_height );
快樂的編碼......
為了避免這個錯誤,你需要使用ViewGroup.LayoutParams
,因為android.support.v7.Toolbar
可以使用它並在mToolbar.getLayoutParams().
上返回它mToolbar.getLayoutParams().
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.