3

如何获得某个布局的测量值,如线性布局或相对布局,其 layout_width 和 layout_height 设置为 wrap_content?使用这种方法

 layout.measure(MeasureSpec.makeMeasureSpec(0,
            MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED));

 layout.layout(0, 0,
            layout.getMeasuredWidth(),
            layout.getMeasuredHeight());

返回空值。我正在尝试从相对布局中创建位图图像,有点像屏幕截图。

4

3 回答 3

5

不要在 onCreate() 方法上执行此操作。尝试这个:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus == true) {
        LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.myLinearLayout);
        int layoutWidth = myLinearLayout.getWidth();
        int layoutHeight = myLinearLayout.getHeight();
    }
}

当尺寸已知时,此方法在 onCreate() 之后调用。

于 2013-03-08T12:19:38.537 回答
1

您可以在视图上使用 getMeasuredWidth() 和 getMeasuredHeight()。

请记住,视图必须首先进行布局。您不能在 onCreate 中执行此操作,因为尺寸尚不清楚。你必须等到它已经布局。

于 2011-05-13T06:56:22.643 回答
0

公共类 AndroidResizeView 扩展 Activity {

TextView textMyTextView;
Button myButton;

RelativeLayout rlayout;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.hightk);

    rlayout = (RelativeLayout) findViewById(R.id.rlayout);

    textMyTextView = (TextView) findViewById(R.id.textView1);

    myButton = (Button) findViewById(R.id.button1);

    myButton.setOnClickListener(new Button.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            updateSizeInfo();
        }
    });
}

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    // TODO Auto-generated method stub
    super.onWindowFocusChanged(hasFocus);
    updateSizeInfo();
}

private void updateSizeInfo() {

    textMyTextView.setText(String.valueOf("Width: "
            + rlayout.getWidth() + "height ::" + rlayout.getHeight()));

}

}

于 2014-01-22T12:24:54.840 回答