如何获得Button的高度和宽度

And*_*Dev 3 android

我创建了一系列按钮.现在我想找到按钮的高度和宽度,为此我使用了getWidth()和getHeight().但问题是它总是返回0.为什么会发生这种情况?我发送了我的代码,请检查是否有任何问题.

    int x,y;
    LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
    LinearLayout rowLayout = null;

    LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1);

    //Create Button
    for (int i = 0; i<6; i++)
    {
        rowLayout = new LinearLayout(this);
        rowLayout.setWeightSum(7);
        layoutVertical.addView(rowLayout, param);   

        for(int j=0; j<7; j++)
        {
            m_pBtnDay[i][j] = new Button(this);             

            rowLayout.addView(m_pBtnDay[i][j], param); 

            m_pBtnDay[i][j].setOnLongClickListener(this);                           

            m_pBtnDay[i][j].setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
            m_pBtnDay[i][j].setTextSize(12);                                
        }
    }
    x =  m_pBtnDay[i][j].getWidth();
    y =  m_pBtnDay[i][j].getHeight();
    Log.d("width", Integer.toString(x));
    Log.d("Height", Integer.toString(y));
    return true;
Run Code Online (Sandbox Code Playgroud)

Mar*_*rco 13

也许你在呼唤getWidth()getHeight()太早:我觉得用户界面一直没有大小和屏幕上的布局尚未...
你可以尝试把这些代码这里面:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    // Call here getWidth() and getHeight()
 }
Run Code Online (Sandbox Code Playgroud)


San*_*ndy 7

其他方式

ViewTreeObserver vto = button.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {

        width = button.getWidth();
        height = button.getHeight();
    }
});
Run Code Online (Sandbox Code Playgroud)