Android 将可绘制对象置于具有背景且无文本的 Button 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21711468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:57:30  来源:igfitidea点击:

Center a drawable in a Button with background and no text

androidbutton

提问by HarryHippo

I have a few buttons in my Android app. They each look kinda like this:

我的 Android 应用中有几个按钮。他们每个人看起来都像这样:

<Button
    android:id="@+id/button_1"
    android:drawableTop="@drawable/an_icon"
    android:background="@drawable/a_background"
    android:layout_width="size_dp"
    android:layout_height="size_dp">
</Button>

Granted, I'm new to Android dev, but I can't figure out how to center the drawable in my button. I've tried the different drawableLocations, margins and padding for the button and its container, as well as drawablePadding, but I can't seem to get it done. Is there a way to center the drawable without abandoning Button for another View?

当然,我是 Android 开发人员的新手,但我不知道如何在我的按钮中将 drawable 居中。我已经为按钮及其容器以及 drawablePadding 尝试了不同的 drawableLocations、边距和填充,但我似乎无法完成。有没有办法在不为另一个视图放弃 Button 的情况下将 drawable 居中?

回答by Tomasz Dzieniak

The easiest solution is to use ImageButtonwidget:

最简单的解决方案是使用ImageButton小部件:

<ImageButton
    (...)
    android:background="@drawable/a_background"
    android:src="@drawable/an_icon"
    />

回答by Sagar Shah

Is there a way to center the drawablewithout abandoning Button

有没有办法在drawable不放弃的情况下居中Button

So you can have both (background & drawable) by using ImageViewas below: (So No need to use Button)

因此,您可以使用ImageView以下方法同时拥有(背景和可绘制):(因此无需使用按钮)

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/an_icon"
    android:background="@drawable/a_background" />

For OnClickof ImageView:

对于OnClickImageView

findViewById(R.id.imageView1).setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
});

回答by razzek

Try this:

尝试这个:

  <Button
        android:id="@+id/button_1"
        android:drawableTop="@drawable/an_icon"
        android:background="@drawable/a_background"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="151dp">
    </Button>