【问题标题】:How to get ImageButton width如何获取 ImageButton 的宽度
【发布时间】:2019-02-13 22:51:42
【问题描述】:

如何将 XML 中设置的 ImageButton 的宽度设为 0,并根据权重获得大小?

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginLeft="10dp"
    android:orientation="horizontal">

    <ImageButton
        android:id="@+id/fluido"
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_marginEnd="10dp"
        android:layout_marginRight="10dp"
        android:tint="@color/icon"
        android:layout_weight="0.33"
        app:srcCompat="@drawable/fluido" />

        <......../>

</LinearLayout>

如何获得这个由权重自动设置的值?

XML 中设置为 0,如果我这样做:imageButton.getWidth();imageButton.getLayoutParams().width(); 都返回 0,就像在 XML 中一样。

【问题讨论】:

  • 使用imageButton.getWidth();,但布局阶段之后 - 你可以使用ViewTreeObserver
  • @pskink 我没听懂,你能解释清楚吗?
  • 那么看ViewTreeObserver官方文档还有什么不清楚的地方?
  • 这个链接会帮助你stackoverflow.com/questions/3591784/…

标签: java android parameters width


【解决方案1】:

可以使用下面的sn-p:

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 

    @Override 
    public void onGlobalLayout() { 
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        } else {
            yourView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        } 
        // Correct view dimensions are here:
        int width  = yourView.getMeasuredWidth();
        int height = yourView.getMeasuredHeight(); 
    } 
});

【讨论】:

  • 这仍然返回 0
  • 我设置 android:layout_width="match_parent" 而不是 0dp 会有所帮助。
【解决方案2】:
Button button;
button = (Button) findViewById(R.id.button);

int buttonWidth = button.getWidth();

// Showing the Result
Toast.makeText(MainActivity.this, ""+buttonWidth, Toast.LENGTH_SHORT).show();

// 布局图像

// 结果

【讨论】:

    【解决方案3】:

    它给出 0 是因为您必须确保存储宽度的整数未声明为 final。

    不应该是这样的: Click to see Image

    【讨论】:

      【解决方案4】:

      你应该使用 addOnPreDrawListener

      view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
      {
          @Override
          public boolean onPreDraw()
          {
              if (view.getViewTreeObserver().isAlive())
                  view.getViewTreeObserver().removeOnPreDrawListener(this);
      
              // put your code here
              return false;
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2014-09-05
        • 1970-01-01
        • 2011-03-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-12
        • 2014-05-01
        • 1970-01-01
        相关资源
        最近更新 更多