How to place text below a Button or a ImageButton?

吃可爱长大的小学妹 提交于 2019-12-11 08:03:37

问题


i'm using Buttons (or ImageButtons) to show the icons of my app. I use this to set the state of the buttons, with a image for the button pressed and another image for the button unpressed:

selector(this, favorites,  R.drawable.icon_star_mark,  R.drawable.icon_star_mark_selected);

public static void selector(Context c, Button b, int normal_image, int pressed_image){
        StateListDrawable states = new StateListDrawable();
        states.addState(new int[] {android.R.attr.state_pressed}, c.getResources().getDrawable(pressed_image));         
        states.addState(new int[] { }, c.getResources().getDrawable(normal_image));      
        b.setBackgroundDrawable(states);
    }

I need to put text below the icon, but i want to learn doing it without using a LinearLayout with a icon and a textview below it. I want to learn doing that if it is possible to achiev it.

This is the way i'm creating the icon:

Button map= new Button(this);
selector(this, map,  R.drawable.icon_map,  R.drawable.icon_map_selected);
map.setText("Map");

The problem is that the text is being displayed above the icon, and not below the icon.

It is possible to achieve that with java code? (placing the text of the icon below the icon without using a linear layout with a textview below the icon)

Thanks in advance


回答1:


It's possible using drawableTop attribute. The selector goes into android:background and the icon into android:drawableTop attr.

<Button
        android:id="@+id/btn"
        style="@style/DashboardButton"
        android:drawableTop="@drawable/any_drawable"
        android:text="@string/any_text" />

Or you can set drawables programatically using button.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);



来源:https://stackoverflow.com/questions/13128895/how-to-place-text-below-a-button-or-a-imagebutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!