How to create really small buttons in android from

2019-03-17 14:09发布

Android default Button class provides a really big button.

button with caption "Save"

There is a lot of wasted space around. Now I want to create really small buttons, that are only slightly bigger than the text/caption. How to do this from code? So far I found the following method, but it is still providing too big buttons and wasting too much space:

A. Create an XML (smallbutton.xml) in the res/layout:

<?xml version="1.0" encoding="utf-8"?>

    style="?android:attr/buttonStyleSmall"
    android:text="color"
    android:padding="0dp"
    android:layout_margin="0dp"

    android:textSize="8dp"
    android:maxHeight="2dp"
    android:maxWidth="2dp"

/>

B. From your code inflate this and add to the view:

Button pickBackColor = (Button) this.getLayoutInflater().inflate(R.layout.smalbutton,null);

...

LinearLayout linLayout = new LinearLayout(this);

linLayout.addView(pickBackColor);

Now the problem is that the button is still too big, it uses too much space around (on the left, right, above, under) of the text.

enter image description here

Any hint how to decrease the size of the button further?

4条回答
混吃等死
2楼-- · 2019-03-17 14:12

try this in your code:

pickBackColor.setWidth(VALUE);
pickBackColor.setHeight(VALUE);
查看更多
我只想做你的唯一
3楼-- · 2019-03-17 14:13

in .xml file... you need to pass small value to layout_height and layout_width in xml file...... try this.

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

Change value as per your requirement...

查看更多
小情绪 Triste *
4楼-- · 2019-03-17 14:21

For your information there is also the default style provided by Android that defines smaller buttons:

style="?android:attr/buttonStyleSmall"

You can also if necessary modify this default style and define custom attributes in your file styles.xml. Here is an example with the modifications described in the question:

<style name="MyButtonStyleSmall" parent="android:Widget.Button.Small">
    <!-- Customizations  -->
    <item name="android:minHeight">0dp</item>
    <item name="android:minWidth">0dp</item>
</style>

Then you just need to call it in the XML:

<Button 
   android:id="@+id/small_button"
   android:text="@string/example"
   android:contentDescription="@string/example_desc"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   style="@style/MyButtonStyleSmall" />
查看更多
劫难
5楼-- · 2019-03-17 14:27

Buttons have a minimal height and width (typically of 48dp respectively 64dp by default). So add

android:minHeight="0dp"
android:minWidth="0dp"

to get really small buttons:

enter image description here

查看更多
登录 后发表回答