gpt4 book ai didi

android - 动态添加 TableRow 与 getMeasuredHeight/getHeight 的问题

转载 作者:太空狗 更新时间:2023-10-29 13:43:45 25 4
gpt4 key购买 nike

我有一个问题。

我希望将行动态添加到 TableLayout。添加这些行时,我需要能够获取 View 的大小,因此我尝试在 onSizeChanged() 期间执行此操作,但新行不显示。所以我尝试了 onFinishInflate(),但是我无法访问大小 (getMeasuredHeight 返回 0)

以下代码的输出显示两行 initial row + onFinishInflate getMeasuredHeight=0。但是,如果我使用 sdk 中的 hierarchyviewer 并按 load view hierarchy 然后我突然在模拟器中看到 3 行 initial row + onFinishInflate getMeasuredHeight=0 + onSizeChanged getMeasuredHeight=270!.

Note: This is using emulator 2.1 hvga landscape, code built with latest sdk, targeting android1.5.


<?xml version="1.0" encoding="utf-8"?>
<com.steelbytes.android.TableHeightTest.TestLinLay
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableLayout
android:id="@+id/table1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:text="initial row"
/>
</TableRow>
</TableLayout>
</com.steelbytes.android.TableHeightTest.TestLinLay>

package com.steelbytes.android.TableHeightTest;

import android.app.Activity;
import android.os.Bundle;

public class TableHeightTest extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}

package com.steelbytes.android.TableHeightTest;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class TestLinLay extends LinearLayout
{
Context mContext;

public TestLinLay(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = context;
}

private void addRow(String funcName)
{
TableLayout tl = (TableLayout)findViewById(R.id.table1);
TableRow tr = new TableRow(mContext);
TextView tv = new TextView(mContext);
tv.setText(funcName+" getMeasuredHeight="+tl.getMeasuredHeight());
tr.addView(tv);
tl.addView(tr);
}

@Override
protected void onFinishInflate()
{
super.onFinishInflate();
addRow("onFinishInflate");
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w,h,oldw,oldh);
addRow("onSizeChanged");
}
}

最佳答案

在调用 getMeasuredWidth/getMeasuredHeight 之前调用 View.measure(int widthMeasureSpec, int heightMeasureSpec)( http://developer.android.com/reference/android/view/View.html#measure%28int,%20int%29 ) 可以很好地测量高度。

关于android - 动态添加 TableRow 与 getMeasuredHeight/getHeight 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2323981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com