Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get height and width of Button

Tags:

android

I have created an array of buttons. Now I want to find the height and width of the button, and for that, I have used getWidth() and getHeight(). But the thing is that it always returns 0. Why is this happening? I have send my code, please check if anything is wrong.

LinearLayout layoutVertical = (LinearLayout) findViewById(R.id.liVLayout);
LinearLayout rowLayout = null;
LayoutParams param = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1);

public static void main(String[] args)
{
    DBFacade dbFacade = new DBFacade();
    dbFacade.pick();
}

//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;
like image 946
AndroidDev Avatar asked Nov 30 '22 07:11

AndroidDev


2 Answers

Probably you are calling getWidth() and getHeight() too early: I think the UI has not been sized and laid out on the screen yet...
You can try to put that code inside this:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    // Call here getWidth() and getHeight()
 }
like image 95
Marco Avatar answered Dec 12 '22 09:12

Marco


Another way

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

        width = button.getWidth();
        height = button.getHeight();
    }
});
like image 20
Sandy Avatar answered Dec 12 '22 07:12

Sandy