首页 > 解决方案 > 即使在应用解决方法后 getWidth() 也会返回 0

问题描述

我的java代码:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        final TextView textView = (TextView) findViewById(R.id.text1);
        final Button button = (Button) findViewById(R.id.button1);
        button.post(new Runnable() {
            @Override
            public void run() {
                int buttonWidth = button.getWidth();
                int textWidth = textView.getWidth();
                button.setWidth(buttonWidth-textWidth);
            }
        });

我的 xml 视图:

 <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Timer"
        android:textSize="16sp"/>

  <TextView
      android:id="@+id/text1"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:padding="8dp"
      android:text="+5"/>

我正在使用this answer中描述的第二种方式。

我想要做的是让按钮填充整个宽度,并为 textView 提供足够的空间。我最近几个月一直在学习 Android,所以如果你能以清晰的方式解释它会很有帮助。

标签: javaandroidandroid-layoutgetter

解决方案


使用 addOnGlobalLayoutListener 代替您链接的解决方案,当我看到这个问题时,这通常对我有用。

myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT > 16) {
                myView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            else {
                myView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
            myView.getWidth();
        }
    });

推荐阅读