【发布时间】:2011-10-11 05:16:42
【问题描述】:
我想创建一个带有图像和文本的 android 按钮,但文本自动居中。如何将文本放置在按钮的底部?
我知道我可以使用相对布局在图像下方放置第二个文本按钮,但我更喜欢最小化代码。
【问题讨论】:
我想创建一个带有图像和文本的 android 按钮,但文本自动居中。如何将文本放置在按钮的底部?
我知道我可以使用相对布局在图像下方放置第二个文本按钮,但我更喜欢最小化代码。
【问题讨论】:
如果我是你,我就不会使用按钮。使用LinearLayout或RelativeLayout,只需给它Button背景(提示:如果你希望它为每个状态有不同的图像,请使用选择器)并将你的TextView放在其中,然后你可以使用drawableLeft,drawableTop等。属性将图片放在您想要的任何一侧。如果您想更好地控制图片相对于文本的位置,请使用一个 TextView 和一个 ImageView。然后在您的 java 中获取对您的布局的引用并像对待按钮一样对待它,使用 setOnClickListener()。
【讨论】:
您可以在按钮上声明要分配图像的位置 (我假设您已经在按钮上有图像):
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- I'm a Button -"
android:drawableTop="@drawable/icon"
/>
你还可以使用 android:drawablePadding(int) 设置文本和图像之间的填充
drawableTop属性可以改成drawableRight、Left、Bottom等,祝你好运!
【讨论】:
Button(而不是ImageButton)上?你的意思是使用drawableTop=吗?
你可以试试这样的
<Button
android:id="@+id/ButtonTest"
android:text="this is text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/icon"
**android:gravity="bottom"**/>
【讨论】:
我认为实现这一点的最简单方法(使用纯 XML)是:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickMethod"
android:orientation="vertical"
android:clickable="true">
<ImageView
android:src="@drawable/YOUR_DRAWABLE"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"/>
<TextView
android:text="@string/YOUR_TEXT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"/>
</LinearLayout>
【讨论】:
你也可以这样做
<LinearLayout
android:id="@+id/image_button_2"
style="@android:style/Widget.Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:gravity="center">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:src="@drawable/ic_gear" />
<TextView
android:id="@+id/image_button_2_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:text="Button 2" />
</LinearLayout>
在你的活动中
final View button2 = findViewById(R.id.image_button_2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
【讨论】: