[英]Android: Drawable inside of button
我有一个我想在其中添加可绘制对象的按钮:
没有可绘制的按钮:
这是我想做的:
具有可绘制的按钮:
我知道android:drawableStart
但这是我在使用它时得到的:
如果有一种方法可以在按钮的边缘上写文本,这将很有用,因为我要放入的drawable有一个unicode字符(表情符号)。
谢谢!
您可以创建自己的按钮:
my_button.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:clickable="true"
android:background="@drawable/selector_button">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:id="@+id/imageView1"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:id="@+id/imageView2"/>
</LinearLayout>
selector_button.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="@android:color/holo_green_dark"/>
<stroke android:width="3dp" android:color="@android:color/white"/>
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@android:color/holo_green_light"/>
<stroke android:width="2dp" android:color="@android:color/white"/>
</shape>
</item>
MyButton.java:
public class MyButton extends FrameLayout {
public MyButton(Context context) {
this(context, null, 0);
}
public MyButton(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
inflate(context, R.layout.my_button, this);
final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyButton, 0, 0);
final Drawable image1 = typedArray.getDrawable(R.styleable.MyButton_image1),
image2 = typedArray.getDrawable(R.styleable.MyButton_image2);
final String text = typedArray.getString(R.styleable.MyButton_txt);
typedArray.recycle();
if (image1 != null) ((ImageView) findViewById(R.id.imageView1)).setImageDrawable(image1);
if (image2 != null) ((ImageView) findViewById(R.id.imageView2)).setImageDrawable(image2);
if (text != null) ((TextView) findViewById(R.id.textView)).setText(text);
}
public void setText(int resId) {
((TextView) findViewById(R.id.textView)).setText(resId);
}}
创建文件“ values / attrs.xml”:
<declare-styleable name="MyButton">
<attr name="image1" format="reference"/>
<attr name="txt" format="string"/>
<attr name="image2" format="reference"/>
</declare-styleable>
并在您的布局中放置代码:
<MyButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:image1="@drawable/image1"
app:image2="@drawable/image2"
app:txt="@string/anyText"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.