有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何获取ImageButton宽度

如何获取在XML中设置为0且大小与权重成正比的ImageButton的宽度

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

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

        <......../>

</LinearLayout>

如何获取由权重自动设置的该值

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


共 (4) 个答案

  1. # 1 楼答案

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

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

  2. # 2 楼答案

    您应该使用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;
        }
    });
    
  3. # 3 楼答案

    可以使用以下代码段:

    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(); 
        } 
    });
    
  4. # 4 楼答案

    Button button;
    button = (Button) findViewById(R.id.button);
    
    int buttonWidth = button.getWidth();
    
    // Showing the Result
    Toast.makeText(MainActivity.this, ""+buttonWidth, Toast.LENGTH_SHORT).show();
    

    //布局图像 enter image description here

    //结果

    enter image description here