我正在尝试获取一个视图的高度,但它一直返回0。
这是我尝试过的方法:
View hourView = View.inflate(mContext, R.layout.calendar_hour_item,null);
hourViewHeight = hourView.findViewById(R.id.mainLayout).getHeight();
我也尝试了 hourViewHeight = hourView.getHeight();
,但是没有成功。
我在这里的 initialize() 方法中调用了这两行代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar_day_screen);
Intent intent = getIntent();
mDate = new DateTime(intent.getStringExtra("date"));
circleIcon = (ImageView) findViewById(R.id.circle);
mHoursLayout = (RelativeLayout) findViewById(R.id.dayLayout);
TopBarUtil topBar = new TopBarUtil(getApplicationContext());
circleIcon.setOnClickListener(topBar.onActionClickListener());
mContext = getApplicationContext();
initialize();
}
这是我的xml布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/mainLayout" android:background="@layout/border">
<TextView android:text="12am" android:id="@+id/hourTextView"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</RelativeLayout>
我希望能获取上述XML布局的高度,但总是返回0。
编辑:我也尝试过以下方法:
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
final View hourView = View.inflate(mContext, R.layout.calendar_hour_item,null);
ViewTreeObserver observer = hourView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
hourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
hourViewHeight = hourView.getHeight();
Log.d(TAG, "hourViewHeight = " + hourViewHeight);
}
});
// hourViewHeight = hourView.findViewById(R.id.mainLayout).getHeight();
// Log.d(TAG, "hourViewHeight = " + hourViewHeight);
}
.measure
方法是不必要的,但是我相信使用getMeasuredHeight()
和getMeasuredWidth()
而不是标准的getHeight()
和getWidth()
是正确的。 - Kevin Coppock