为什么我无法在字段中指定宽度和高度值?当我使用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();
}
}
答案 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();
}
});