1、新建image_text_button.xml文件
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/image_text_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:animateLayoutChanges="true"
android:background="@drawable/home_selector"
android:orientation="vertical">
<ImageButton
android:id="@+id/button_icon"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:animateLayoutChanges="true"
android:background="@android:color/transparent"
android:scaleType="fitCenter">
</ImageButton>
<TextView
android:id="@+id/button_text"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:animateLayoutChanges="true"
android:textColor="@color/white"
android:scaleType="fitCenter">
</TextView>
</LinearLayout>
</merge>
2、新建ImageTextButton.java
public class ImageTextButton extends LinearLayout {
private Context mContext;
private ImageButton mIcon;
private TextView mText;
private int mIconResourceId;
public ImageTextButton(Context context) {
super(context);
}
public ImageTextButton(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mContext = context;
View.inflate(context, R.layout.image_text_button, this);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CarImageTextButton);
mIcon = findViewById(R.id.button_icon);
mIcon.setScaleType(ImageView.ScaleType.CENTER);
mIcon.setClickable(false);
mIconResourceId = typedArray.getResourceId(R.styleable.CarImageTextButton_icon, 0);
mIcon.setImageResource(mIconResourceId);
mText = findViewById(R.id.button_text);
mText.setClickable(false);
String text = typedArray.getString(R.styleable.CarImageTextButton_text);
mText.setText(text);
}
}
3、在attrs.xml文件中新增属性
<!-- Allow for custom attribs to be added to a image text button -->
<declare-styleable name="CarImageTextButton">
<!-- icon to be rendered (drawable) -->
<attr name="icon" format="reference"/>
<attr name="text" format="string"/>
</declare-styleable>
4、运用,使用icon和text属性配置图片和文字
需要在根目录标签新增xmlns:demo="http://schemas.android.com/apk/res-auto"属性
<com.ad.demo.view.ImageTextButton
android:id="@+id/go_home"
style="@style/ImageTextButton"
demo:icon="@drawable/b_poi_10010_67_hl"
demo:text="回家"
android:paddingStart="@dimen/default_6" />
本文介绍了如何创建一个自定义的ImageTextButton组件,包括XML布局文件的设计、Java类的实现以及如何在attrs.xml文件中定义自定义属性,并展示了如何在实际应用中使用这些属性来配置按钮的图标和文本。
1万+





