为什么我不能在字段中指定宽度和高度值?

时间:2015-09-09 14:17:56

标签: android

为什么我无法在字段中指定宽度和高度值?当我使用Toast类测试以下代码时,字段仍然具有0值。似乎在运行post方法后,值将被销毁。我该如何防止此事件发生?

public class MainActivity extends Activity {
RelativeLayout re;
int width,height;
  protected void onCreate(Bundle bundle) {
  super.onCreate(bundle);
  setContentView(R.layout.activity_main);
  re = (RelativeLayout) findViewById(R.id.re);
  re.post(new Runnable() {
  @Override
  public void run() {
  width=re.getWidth();
        height=re.getHeight();
    }
});
 Toast.makeText(getApplicationContext(), String.valueOf(width) + "  " + String.valueOf(height), Toast.LENGTH_LONG).show();
}
}

1 个答案:

答案 0 :(得分:1)

您可以尝试使用以下代码..

re.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

  public void onGlobalLayout() {
    height = re.getHeight();
    width = re.getWidth();
    Toast.makeText(getApplicationContext(), String.valueOf(width) + "  " + String.valueOf(height), Toast.LENGTH_LONG).show();
  }
});