android:以编程方式获取viewHeight

android:以编程方式获取viewHeight,android,Android,我试图获取视图的高度,但它始终返回0 这就是我尝试过的: View hourView = View.inflate(mContext, R.layout.calendar_hour_item,null); hourViewHeight = hourView.findViewById(R.id.mainLayout).getHeight(); 我还尝试了hourViewHeight=hourView.getHeight()也一样,但没有乐趣 我在位于此处的initialize()方法中调用这两行

我试图获取视图的高度,但它始终返回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>

您已将高度设置为
wrap\u content
,但未填充该内容。因此,它将显示为0。

请尝试

hourView.measure(hourView.getWidth(), hourView.getHeight());
hourView.getMeasuredHeight()

在第一个示例中,它不起作用,因为当您查询它们时,视图仍然没有执行布局和测量步骤。您只告诉视图它在布局中的“行为”,但它仍然没有计算每个视图的放置位置

(类似问题:)


在您发布的第二个示例中,我认为您没有将视图添加到活动中,因此活动不会绘制视图,因此,您永远不会阅读该日志消息。调用
setContentView
addView
到某个布局。

我尝试在类似100dip的地方指定一个高度,但它仍然返回0您正在指定linearlayout的高度?如上面的xml代码所示,我使用relativelayout。我自己使用android:layout\u height=“50dip”指定了高度,但仍然不起作用。我还尝试过使用onStart中粘贴的OnGlobalYoutListener,即使这样也不起作用。为什么仅仅返回视图高度就要做这么多的工作!它是wrap_content,具有包含文本的子TextView,设置为wrap_content。一旦被测量,它就有了一个大小。我认为如果在GlobalLayoutListener中有这个方法,就不需要使用
.measure
方法,但我相信这是正确的,因为使用getMeasuredHeight()和getMeasuredWidth()而不是标准的getHeight()和getWidth()。
hourView.measure(hourView.getWidth(), hourView.getHeight());
hourView.getMeasuredHeight()