【问题标题】:Set height of Toolbar half of attr/actionBarSize in xml在 xml 中设置工具栏一半 attr/actionBarSize 的高度
【发布时间】:2017-08-04 07:09:11
【问题描述】:

无论如何设置“android.support.v7.widget.Toolbar”的高度是预定义属性的一半,例如布局xml文件中的“?android:attr/actionBarSize”? 事实上,我希望工具栏的高度类似于:

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height=("?android:attr/actionBarSize")/2
    >

【问题讨论】:

  • 没有。你不能。您需要以编程方式设置或在xml文件中手动应用
  • 通常工具栏高度为 50dp 到 55dp,因此您可以根据自己的需要进行测量,它可以是 25dp 或 26dp,适用于所有设备。
  • @9sol,这是不正确的。它接受 56dp、48dp(横向)、64dp(在 sw600dp 上)。
  • 我不会将任何值硬编码为默认值,因为新的 android API 可能会更改(或在其他设备上有所不同),而是以编程方式设置它 - 获取 android:attr/actionBarSize 的值,乘以并设置.
  • @MatPag,正如 OP 在his comment 中提到的那样,他了解编程解决方案,因此他特别对 XML 解决方案感兴趣。恕我直言,提供了一个不完全回答问题的答案(编程方式,就像你所做的那样),并不意味着应该改变这个问题。感谢合作。

标签: android android-layout android-view android-resources android-styles


【解决方案1】:

无法在 xml 中执行算术操作。

如果你想通过xml给出值,那么你必须执行以下操作:

  1. 在values/dimes.xml 中定义一个变量halfActionBar 并使其为28dp(原来是56dp)。
  2. 在values-land/dimes.xml 中定义一个变量halfActionBar 并使其为24dp(原来是48dp)。
  3. 在values-sw600dp-v13/dimes.xml 中定义一个变量halfActionBar 并使其为32dp(原来是64dp)。

在您的styles.xml 主题中。

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:actionBarSize">@dimen/halfActionBar</item>
    ...
</style>

然后在你的布局中:

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="?android:attr/actionBarSize"/>

请注意,这是一个糟糕的解决方案,因为它取决于平台实现。我建议 get actionBarSize 来自 java/kotlin 代码(不是来自 xml)。

【讨论】:

  • 我不喜欢这个方案,在Android平台变化时很容易出错。我认为以有效方式做到这一点的唯一方法是使用 Java 代码。回家后我会尝试一些不同的东西。
  • @MatPag,完全同意。
【解决方案2】:

你不能在 XML 中做到这一点,但如果你想以编程方式尝试这样的事情,我从 here 那里得到了这个想法

//themedContext is an Activity or a Context which has a Theme attached,
//you can't use Application context for this
final TypedArray array = themedContext.getTheme().obtainStyledAttributes(
                new int[] { android.R.attr.actionBarSize });
int actionBarSize = (int) array.getDimensionPixelSize(0, -1);
array.recycle();

然后将其应用于工具栏,您可以这样做:

Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);

RelativeLayout.LayoutParams layoutParams = 
                 (RelativeLayout.LayoutParams) myToolbar.getLayoutParams();
//half the height of toolbar prior to set its value
layoutParams.height = (int)(actionBarSize / 2);
myToolbar.setLayoutParams(layoutParams);

setSupportActionBar(myToolbar);

PS:不要忘记这个属性值会随着设备旋转而改变,所以每次设备从纵向变为横向,反之亦然时,你都应该设置这个自定义值。

【讨论】:

  • 我知道我可以通过编程来做到这一点。问题是关于在 xml 文件中定义该值,因为它似乎不可能
  • 不,不可能以可靠的方式使用 XML,您没有在问题中提供任何暗示您不打算尝试使用 Java 代码,这就是我发布答案的原因
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
  • 2015-05-13
  • 1970-01-01
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多