我想创建一个自定义按钮,这个按钮最好能在左侧显示图像,在右侧显示文本框。我该如何实现?
创建一个可点击的视图,其中使用按钮图形作为背景,该视图包含ImageView和TextView。
<RelativeLayout
android:clickable="true"
android:background="@android:drawable/btn_default"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/image"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="@android:drawable/ic_input_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ImageView>
<TextView
android:id="@+id/text"
android:text="Sample text"
android:textAppearance="?android:attr/textAppearanceButton"
android:layout_toRightOf="@id/image"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</RelativeLayout>
创建自己的类,扩展RelativeLayout,将内容视图设置为上述内容,添加自定义方法以设置文本、图片等,这就是全部。 使用你自己的自定义布局。
你可以使用如下代码来完成该任务:
<Button
android:layout_width="fill_parent"
android:layout_height="50dp"
android:id="@+id/btnLogin"
android:text="@string/text"
android:gravity="center"
android:drawableLeft="@drawable/your_image"
android:background="@drawable/login"/> // this is for nice background - *.9.png
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape>
<solid android:color="#f3ae1b" />
<stroke android:width="1dp" android:color="#bb6008" />
<corners android:radius="3dp" />
<padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />
</shape>
</item>
<item>
<shape>
<gradient
android:startColor="#f3ae1b"
android:endColor="#bb6008"
android:angle="270" />
<stroke
android:width="1dp"
android:color="#bb6008" />
<corners
android:radius="4dp" />
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
</item>
</selector>
编辑:用于膨胀的代码
private LayoutInflater mInflater;
mInflater = LayoutInflater.from(this);
public LinearLayout yourButton;
yourButton = (LinearLayout) mInflater.inflate(R.xml.yourButton, null);
android:drawableLeft="@drawable/image"
您可以使用NoboButton来实现这一点
一种简单快捷的方式,用于创建带有图标、半径和背景的Android按钮
库地址 https://github.com/alex31n/NoboButton
截图 https://raw.githubusercontent.com/alex31n/NoboButton/master/Assets/button_screenshot.jpg