我试图获得一个视图的高度,它一直返回0.
这是我尝试过的:
View hourView = View.inflate(mContext, R.layout.calendar_hour_item,null);
hourViewHeight = hourView.findViewById(R.id.mainLayout).getHeight();
Run Code Online (Sandbox Code Playgroud)
我也试过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();
}
Run Code Online (Sandbox Code Playgroud)
这是我的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>
Run Code Online (Sandbox Code Playgroud)
我basicllay想要获得上面的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);
}
Run Code Online (Sandbox Code Playgroud)
尝试
hourView.measure(hourView.getWidth(), hourView.getHeight());
hourView.getMeasuredHeight()
Run Code Online (Sandbox Code Playgroud)
在第一个示例中它不起作用,因为当您查询它们时,视图仍然没有执行布局和测量步骤。您只告诉视图它将如何在布局中“表现”,但它仍然没有计算出每个视图的放置位置。
(类似问题:How to get the width and height of an android.widget.ImageView?)
在您发布的第二个示例中,我认为您没有将视图添加到活动中,因此活动不会绘制它,因此您永远不会阅读该日志消息。调用setContentView或addView某些布局。
| 归档时间: |
|
| 查看次数: |
10030 次 |
| 最近记录: |