开发者

Get RelativeLayout dimensions

How do I get the measurements of a certain layout like linearlayout or rela开发者_如何学Ctivelayout with its layout_width and layout_height set to wrap_content? using this method

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

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

returns null. I'm trying to create a bitmap image out of the relativelayout, kinda like a screenshot.


Don't do it on the onCreate() method. Try this:

@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();
    }
}

This method is called after onCreate(), when the sizes are already known.


You can use getMeasuredWidth() and getMeasuredHeight() on your view.

Remember the view has to have been layout first. You just CANNOT do it in onCreate, because the sizes are not known yet. You have to wait until it has been layout.


public class AndroidResizeView extends 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()));

}

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜