Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

android - How to get height and width of Button

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...