gpt4 book ai didi

android - 如何检索 View 的尺寸?

转载 作者:IT老高 更新时间:2023-10-28 12:52:51 26 4
gpt4 key购买 nike

我有一个由 TableLayout、TableRow 和 TextView 组成的 View 。我希望它看起来像一个网格。我需要得到这个网格的高度和宽度。 getHeight()getWidth() 方法总是返回 0。当我动态格式化网格以及使用 XML 版本时会发生这种情况。

如何检索 View 的尺寸?


这是我在 Debug 中用来检查结果的测试程序:

import android.app.Activity;
import android.os.Bundle;
import android.widget.TableLayout;
import android.widget.TextView;

public class appwig extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maindemo); //<- includes the grid called "board"
int vh = 0;
int vw = 0;

//Test-1 used the xml layout (which is displayed on the screen):
TableLayout tl = (TableLayout) findViewById(R.id.board);
tl = (TableLayout) findViewById(R.id.board);
vh = tl.getHeight(); //<- getHeight returned 0, Why?
vw = tl.getWidth(); //<- getWidth returned 0, Why?

//Test-2 used a simple dynamically generated view:
TextView tv = new TextView(this);
tv.setHeight(20);
tv.setWidth(20);
vh = tv.getHeight(); //<- getHeight returned 0, Why?
vw = tv.getWidth(); //<- getWidth returned 0, Why?

} //eof method
} //eof class

最佳答案

我相信 OP 早已不复存在,但如果这个答案能够帮助 future 的搜索者,我想我会发布一个我找到的解决方案。我已将此代码添加到我的 onCreate() 方法中:

已编辑: 2011 年 7 月 5 日以包含评论中的代码:

final TextView tv = (TextView)findViewById(R.id.image_test);
ViewTreeObserver vto = tv.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

@Override
public void onGlobalLayout() {
LayerDrawable ld = (LayerDrawable)tv.getBackground();
ld.setLayerInset(1, 0, tv.getHeight() / 2, 0, 0);
ViewTreeObserver obs = tv.getViewTreeObserver();

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
obs.removeOnGlobalLayoutListener(this);
} else {
obs.removeGlobalOnLayoutListener(this);
}
}

});

首先,我获得了对 TextView 的最终引用(在 onGlobalLayout() 方法中访问)。接下来,我从 TextView 中获取 ViewTreeObserver,并添加一个 OnGlobalLayoutListener,覆盖 onGLobalLayout(似乎没有成为在此处调用的父类(super class)方法...)并将我的代码添加到此监听器中,这需要了解 View 的测量值。对我来说一切正常,所以我希望这能有所帮助。

关于android - 如何检索 View 的尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4142090/

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