【问题标题】:How can I ensure Android buttons have the same height when they are in different layouts当Android按钮在不同的布局中时,如何确保它们具有相同的高度
【发布时间】:2013-10-14 00:26:46
【问题描述】:

我有一个包含两个Buttons 和一个TextView 的视图。它们是分层的,使用RelativeLayout,如下所示:

                  +-----------+
__TextView___     | Button 1  |
                  +-----------+
+-----------+
| Button 2  |
+-----------+

这里的关键是 TextView 和 Button 1 具有相同的高度,由 Button 1 上的 layout_alignToplayout_alignBottom 强制执行

按钮 2 被限制为与 TextView 具有相同的宽度(使用 layout_alignLeftlayout_alignRight)。

问题是我还希望它具有与按钮 1 相同的高度,使用如下:

layout_height="@id/button_1"

我可以完全通过使用布局来实现这一点吗?

如果没有,我是否可以在 Activity 中部署一些代码,使用视图强制此 post 布局但在显示之前?

我真的很想避免创建一个特殊的View 来实现这一点。

在 iOS 领域,我可以具体说明各种控件具有相同的高度或宽度,但我看不到在 Android 中执行此操作的方法。

【问题讨论】:

  • 如果你对两个按钮使用 android:layout_height="wrap_content" 和 android:textSize=10sp 或相同的字体大小,我猜你的按钮可以有相同的高度
  • @MaulikSheth 这是真的,但我想避免显式设置大小,我希望大小与输入 EditText 相关
  • 使用与设备无关的像素(倾角)进行测量。该系统将确保在不同的设备和密度上具有相同的尺寸。

标签: android android-layout view height android-relativelayout


【解决方案1】:

试着把它放在你的活动 onCreate 方法中

Button button1 = (Button) findViewById(R.id.button_1);
Button button2 = (Button) findViewById(R.id.button_2);
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
relativeLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        relativeLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);

        RelativeLayout.LayoutParams btParams = (RelativeLayout.LayoutParams) button2.getLayoutParams();
        int height = button1.getHeight();
        btParams.height = height;
        button2.setLayoutParams(btParams);
    }
});

【讨论】:

    猜你喜欢
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多