getWidth() returns 0 即使在应用变通方法之后

getWidth() returns 0 even after applying a workaround

我的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 中描述的第二种方式。

我想要做的是让按钮填充整个宽度,刚好够 space 用于 textView。我最近几个月一直在学习 Android,所以如果你能以一种清晰的方式解释它会很有帮助。

使用您链接的解决方案中的 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();
        }
    });

您可以使用权重为 1 的按钮和文本视图来包装内容的线性布局。

试试这个:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="some text" />

</LinearLayout>