Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

How To Set Height & Width Of A Button?

I Want to set height and width of a button so that it will automically set itself in any android screen size. I used following function but the app unfortunately stop working.

public void setButton() {

    DisplayMetrics metrics = new DisplayMetrics();    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int hp = metrics.heightPixels;
    int wp = metrics.widthPixels;
    Button btn = (Button) findViewById(R.id.btn);
    ViewGroup.LayoutParams params = A.getLayoutParams();
    params.width = (int) (wp / 9.0);
    params.height =  (int) (hp / 11.5);
    btn.setLayoutParams(params);

}

I have even used this line but the problem still remains there.

btn.setLayoutParams(new ViewGroup.LayoutParams((int) (wp / 9.0), (int) (hp / 11.5)));

So Plz help me....

2 Answers

Johan Prieto
Johan Prieto
6,513 Points

Hi there, I am not exactly sure what your trying to do, but if you want to set the parameters yourself you can do the following:

android:layout_width="100dp" android:layout_height="50dp"

or you can use for example:

android:layout_width="match_parent" android:layout_height="wrap_content"

which would probably look better on most devices. I hope this helps, again I am not sure if i understood your question completely.

I want to set these values in 'java' file not in 'XML' file. If there is any code than please tell me

Johan Prieto
Johan Prieto
6,513 Points

Hey again, Here is the link to the button reference, maybe this will help. http://developer.android.com/reference/android/widget/Button.html#Button(android.content.Context)

Let me know how it goes :)