获取RelativeLayout维度

时间:2011-05-13 06:52:13

标签: android android-layout android-image

如何将layout_width和layout_height设置为wrap_content来测量某个布局(如linearlayout或relativelayout)?使用这种方法

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

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

返回null。我正试图从relativelayout创建一个位图图像,有点像截图。

3 个答案:

答案 0 :(得分: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()之后调用此方法,此时已知大小。

答案 1 :(得分:1)

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

请记住,视图必须先布局。你只是不能在onCreate中这样做,因为尺寸尚不清楚。你必须等到它布局。

答案 2 :(得分: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()));

}

}