【问题标题】:set Toolbar height programmatically Android以编程方式设置工具栏高度 Android
【发布时间】:2015-09-14 20:25:56
【问题描述】:

我正在尝试通过这种方式以编程方式设置工具栏的高度:

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中设置高度。

【问题讨论】:

    标签: android android-layout android-xml android-toolbar android-viewgroup


    【解决方案1】:

    试试这个 -

    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mToolbar.getLayoutParams();
    layoutParams.height = 42;
    mToolbar.setLayoutParams(layoutParams);
    

    对我来说很好用。

    如果上面的代码仍然不起作用,请尝试在最后添加这一行 -

    mToolbar.requestLayout();
    

    以上行将强制您的工具栏重新测量所有内容。您的代码可能无法正常工作,因为您试图在布局膨胀后更改高度。在这种情况下,您需要强制您的视图重新测量所有内容。查看以下方法以获取更多信息 - requestLayout()、invalidate() 和 forceLayout()。在更改 LayoutParams 时,这三种方法很方便,但价格不菲。如果你的 Layout 很重并且里面有很多子视图,调用这些方法中的任何一个都会影响你的应用程序的性能,特别是在低端设备上。因此,请务必谨慎使用这些方法。

    您提到的崩溃正在发生,因为您的工具栏是根视图的子视图,而您的根视图是 RelativeLayout。希望对您有所帮助。

    另外,请不要遵循 Silambarasan Poonguti 的回答,因为它有点模棱两可。如果您尝试访问子 LayoutParams,则需要 LayoutParams 强制转换。甚至 View 也有自己的 LayoutParams,您必须将其强制转换为父或根 LayoutParams。如果您的 Toolbar 是 RelativeLayout 的子视图,则将 LayoutParams 转换为 Toolbar.LayoutParams 将使应用程序崩溃,您必须将 LayoutParams 转换为 RelativeLayout.LayoutParams

    【讨论】:

    • 您不应该将 layoutParams 转换为 RelativeLayout.LayoutParams,这是不安全的转换 + 高度在 ViewGroup.LayoutParams 中定义,因此:ViewGroup.LayoutParams layoutParams = mToolbar.getLayoutParams();
    【解决方案2】:

    试试这个...

    工具栏有自己的LayoutParams。您不能将其转换为 RelativeLayout。

        Toolbar.LayoutParams params = (Toolbar.LayoutParams)mToolbar.getLayoutParams();
        params.height = 42;
        mToolbar.setLayoutParams(params);
    

    如果您想在运行时设置工具栏的高度,只需这样做,

        int expected_height = your value;
        mToolbar.setMinimumHeight(expected_height );
    

    【讨论】:

    • 谢谢你的回答,我也试过那个代码,但它给出了同样的例外。同样 setMinimumHeight 甚至在最小高度较小的情况下也不会获得工具栏的默认最小高度
    • 这不是 LayoutParams 的工作方式。甚至 View 也有自己的 LayoutParams,您必须将其强制转换为父 LayoutParams 或根 LayoutParams。如果您的 Toolbar 是 RelativeLayout 的子视图,则将 LayoutParams 转换为 Toolbar.LayoutParams 将使应用程序崩溃,您必须将 LayoutParams 转换为 RelativeLayout.LayoutParams
    【解决方案3】:

    为避免错误,您需要使用ViewGroup.LayoutParams,因为android.support.v7.Toolbar 使用它并在mToolbar.getLayoutParams(). 上返回它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      • 1970-01-01
      • 2013-12-15
      • 2016-07-01
      相关资源
      最近更新 更多