【问题标题】:Cant set LayoutParams to Toolbar无法将 LayoutParams 设置为工具栏
【发布时间】:2015-04-28 18:01:39
【问题描述】:

尝试为我的工具栏设置布局参数时,我遇到了奇怪的异常。

 java.lang.ClassCastException: android.support.v7.widget.Toolbar$LayoutParams cannot be cast to android.widget.LinearLayout$LayoutParams

我想在工具栏的右侧放置一个内部视图,但由于 xml layout_gravity 属性无法正常工作(请参阅question),我正在尝试以编程方式进行。
我的代码如下所示:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setLayoutParams(new Toolbar.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT,
        Gravity.CENTER | Gravity.RIGHT));
setSupportActionBar(toolbar);

如果我将LinearLayout.LayoutParams 的实例设置为布局参数,工具栏就会消失。 我会很感激任何帮助

【问题讨论】:

  • 你解决了吗?

标签: android android-appcompat


【解决方案1】:

抛出异常是因为您试图将 LayoutParams 强制转换为它们不继承的类,因此出现 Class Cast 异常。要解决这个问题,请使用 LinearLayout.LayoutParams 而不是

 new LinearLayout.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT,
    ViewGroup.LayoutParams.WRAP_CONTENT,
    Gravity.CENTER | Gravity.RIGHT));

// Toolbar height is 56dp as per material design guidelines

new LinearLayout.LayoutParams(
    ViewGroup.LayoutParams.MATCH_PARENT,
    56,
    Gravity.CENTER | Gravity.RIGHT));

【讨论】:

    【解决方案2】:

    设置特定高度:

    new LinearLayout.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        80,
        Gravity.CENTER | Gravity.RIGHT);
    

    或将项目添加到您的工具栏,使其不为空,wrap_content 实际上有一些东西要包装。

    【讨论】:

    • 按照您提供的设置特定高度后,工具栏也会消失。而且我的工具栏中实际上有一个 TextView...
    • @Bolein95 你的代码暗示你自己隐藏它:getSupportActionBar().hide();
    • 抱歉,那是列表中不必要的部分。稍后我再展示一次
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 2021-01-11
    相关资源
    最近更新 更多