【问题标题】:How to measure the width of view in android如何在android中测量视图的宽度
【发布时间】:2013-03-20 05:08:58
【问题描述】:

我在具有水平方向的线性布局中有两个文本视图。文本视图的宽度是 wrap_content。如果两个文本视图的宽度之和小于屏幕宽度就可以了。如果宽度的总和超过屏幕宽度,那么我需要将方向从水平更改为垂直。

我尝试在活动的 onCreate 中使用 getWidth(),但它返回 0。我可以尝试使用 onSizeChanged() 函数创建自定义视图,但我正在使用两个文本视图,所以我不确定当 onSizeChanged() 合二为一时文本视图不会确保完全绘制另一个文本视图以获得宽度。任何建议都对我很有帮助。

<LinearLayout android:id="@+id/status_container"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="horizontal"> 
    <TextView android:id="@+id/view1" 
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
    <TextView android:id="@+id/view2"
                    android:layout_height="wrap_content"
        android:layout_width="wrap_content"/>
</LinearLayout>

// In OnCreate() function
TextView view1 = (TextView) findViewById(R.id.view1);
TextView view2 = (TextView) findViewById(R.id.view2);
view1.setText("Good Morning,");
view2.setText("I am Ron");
int view1_width = view1.getWidth();
int view2_width = view2.getWidth();
if ((view1_width + view2_width) > screen_width) {
     // Change the Linear Layout orientation to Vertical
}

这里 view1_width 和 view2_width 返回 0。我想检查 view1_width + view2_width 是否大于屏幕宽度,然后我需要将方向更改为垂直,否则水平方向就可以了。

-罗恩

【问题讨论】:

  • 目标是什么?两者的 weight="1" 将为您提供两个元素,每个元素都占屏幕的一半
  • 你能把你在 onCreate() 中的代码贴出来吗?
  • 您不能在 onCreate() 中使用 getWidth(),因为 GUI 尚不存在。在 onStart() 中试一试
  • @njzk2 目标是让两个文本视图的宽度在运行时运行,如果是这样,我需要检查宽度是否大于屏幕大小,将文本视图更改为垂直对齐。 “AT-Daniel”我已经编辑了问题并发布了我尝试在 onStart() 中使用的 sn-p “AT-Vicki”,但是我如何确保两个文本视图都被渲染,以便 getWidth() 给出的宽度适用于两个文本框。也感谢大家的回复。
  • 也许这对你有帮助。 textview.getPaint().measureText(text) _ 给出特定文本的 textview 的大小。

标签: android android-layout android-widget


【解决方案1】:

将此添加到您的活动的 onCreate

ViewTreeObserver vto = layout.getViewTreeObserver();
     vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
         @Override
             public void onGlobalLayout() {
                 //You should be able to get the width and height over here.

                 layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
             }
     });

【讨论】:

    猜你喜欢
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 2011-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多