2011-05-13 119 views
3

如何通過layout_width和layout_height設置爲wrap_content來獲取諸如linearlayout或relativelayout之類的特定佈局的測量結果?使用此方法獲取RelativeLayout尺寸

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

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

返回null。我試圖從relativelayout創建一個位圖圖像,有點像截圖。

回答

1

您可以在視圖上使用getMeasuredWidth()和getMeasuredHeight()。

請記住,視圖必須先佈局。你只是不能在onCreate中做,因爲尺寸還不知道。你必須等到它已經佈局。

+0

如果有什麼佈局只從XML膨脹? – louieansonng

+0

我使用這段代碼來膨脹'RelativeLayout layout =(RelativeLayout)getLayoutInflater()。inflate(R.layout.pointer,null);' – louieansonng

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()之後調用此方法。

+0

謝謝。我有一個類似的問題,因爲我試圖在onCreate中進行測量。這個線程解決了我的問題。 – Simon

0

公共類AndroidResizeView延伸活動{

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

} 

}