Karthik Balakrishnan
Karthik Balakrishnan

Reputation: 4383

Android layouts - button size

This is my code for the button. Thing is, it's the same size on all devices. It's big on small ones and small on big ones. How do I alter its size relatively? Here's my code.

<Button
        android:id="@+id/button1"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_margin="3dp"
        android:background="@drawable/blue_gradient"
        android:layout_alignRight="@+id/relativeLayout1"
        android:layout_alignTop="@+id/relativeLayout1"/>

I would like the size to be consistent, depending upon the device's resolution.

EDIT I want the buttons to be square.

Upvotes: 0

Views: 225

Answers (3)

mirenibg
mirenibg

Reputation: 106

You might want to try using image buttons with different sized images according to screen resolution (Android, (newbie) different res imagebuttons).

If you use LinearLayout with android:weightSum="2.0" and you set all of your image buttons with android:layout_weight="1" you will have their width/height exactly 50% of the LinearLayout according to the LinearLayout orientation.

Upvotes: 0

Karakuri
Karakuri

Reputation: 38585

You are specifying the width and height in dp, or density-independent pixels. This unit of measure is designed to produce the same physical size on all devices regardless of pixel density, because pixel density varies by device. You can also use either of the following values for layout_width and layout_height:

  • wrap_content makes the view large enough to hold its content.
  • match_parent uses the corresponding dimension (width or height) of its parent view.

Also with any of these you can stil specify padding and margins, a la the typical box model.

Android currently does not support percentage style measurements, like making the width be 60% of the available width. The closest you can get to that is using a LinearLayout and specifying layout_weight values for its child views.

If you want finer control over the size of a view, you can subclass it and override the onMeasure method, which is where you would calculate the size of the view and set its width and height by calling setMeasuredDimension(w, h). Here's an example of someone doing just that: https://stackoverflow.com/a/3147157/1207921

Upvotes: 1

Mohsin Naeem
Mohsin Naeem

Reputation: 12642

the best way is to use

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

It manages size for all devices very well.

For square buttons you need to set width/height in the code. this will help you.

Upvotes: 0

Related Questions