【问题标题】:Make layout width equal height?使布局宽度等于高度?
【发布时间】:2012-04-21 21:24:47
【问题描述】:

我想要一个宽度=fill_parent 的 ImageView,高度应该是宽度。我不确定是否有办法在 xml 中指定,是创建自己的 ImageView 派生类的唯一选择吗?:

public class MyImageView extends ImageView {

    // Just return whatever the current width is?
    private int measureHeight(int measureSpec) {
        return getWidth();
    }
}

这是要走的路,还有其他选择吗? (我不确定上述是否正确,例如不确定宽度测量是否发生在高度测量之前)

谢谢

【问题讨论】:

  • 如果将宽度设置为 fill_parent,getWidth() 方法将返回 0。这种方法不起作用。

标签: android


【解决方案1】:

可以通过方法获取宽度

imageView.getMeasuredWidth();

所以,你可以设置它的高度

imageView.setLayoutParams(new LayoutParams(imageView.getMeasuredWidth(), imageView.getMeasuredWidth()));

【讨论】:

  • 您将在布局过程中的哪个位置设置它(即:哪种方法)?
【解决方案2】:

使布局高度等于宽度:

digulino's answer(至少在我的情况下)的问题是,如果您想在开始时更改尺寸,getMeasuredWidth() 将返回 0,因为尚未绘制视图。

您仍然可以通过使用Runnable() 线程来做到这一点,如下所示:

FrameLayout frame = (FrameLayout)findViewById(R.id.myFrame);
frame.post(new Runnable() {
    @Override
    public void run() {
        RelativeLayout.LayoutParams lparams;
        lparams = (RelativeLayout.LayoutParams) frame.getLayoutParams();
        lparams.height = frame.getWidth();
        frame.setLayoutParams(lparams);
        frame.postInvalidate();
    }
});

重要提示: 此示例假设您的视图是RelativeLayout 内的FrameLayout。为其他布局相应地更改它。

【讨论】:

  • 如果宽度设置为例如“match_parent”(-1),这将不起作用。仅当您先前为该布局指定了数字宽度时,它才会起作用。
  • 很好,所以您之前指定了布局宽度。但它在其他情况下不起作用(我刚刚测试过)。
猜你喜欢
  • 1970-01-01
  • 2019-04-17
  • 1970-01-01
  • 2011-07-23
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 2013-02-16
相关资源
最近更新 更多