gpt4 book ai didi

android - 在 Android 中如何获取设置为 Wrap_Content 的 Textview 的宽度

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:21:46 24 4
gpt4 key购买 nike

我正在尝试将文本添加到我已将其宽度设置为 Wrap_content 的 TextView 中。我正在尝试获取此 TextView 的宽度。但它在所有情况下都显示为 0。将文本设置到 TextView 后,如何获取 TextView 的宽度。

代码如下:

        LinearLayout ll= new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll.addView(tv);
tv.setText("Hello 1234567890-0987654321qwertyuio787888888888888888888888888888888888888888888888888");
System.out.println("The width is == "+tv.getWidth());// result is 0
this.setContentView(ll);

请推荐。提前致谢。

最佳答案

具有动态宽度/高度的 View 只有在布局过程完成后才能获得正确的尺寸(http://developer.android.com/reference/android/view/View.html#Layout)。
您可以将 OnLayoutChangeListener 添加到您的 TextView 并在那里获取它的大小:

tv.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
final int width = right - left;
System.out.println("The width is == " + width);
});

关于android - 在 Android 中如何获取设置为 Wrap_Content 的 Textview 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16021764/

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