【发布时间】:2019-09-10 08:13:02
【问题描述】:
我有自定义图标化按钮,我想在我的项目中使用它,但我需要访问它的子元素以在 XML 中设置文本。如何做到这一点?
<include
android:id="@+id/leaveBtn"
layout="@layout/iconified_button"
style="@style/button_rounded_colorized"
/>
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/button_rounded_colorized">
<ImageView
android:id="@+id/buttonIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="@dimen/padding_small"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/arrow" />
<TextView
android:id="@+id/buttonText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Text"
android:textAllCaps="true"
android:textColor="@color/colorText"/>
</LinearLayout>
我还希望能够更改包含布局中的按钮样式。我不想在 iconified_button 布局 xml 中使用静态样式。
更新:
制作自定义类扩展LinearLayout上方的膨胀布局,并通过attrs.xml中的自定义参数设置Button文本和ImageView图标,这些参数可以在XML中访问。
<com.project.utils.IconifiedButton
android:id="@+id/leaveBtn"
style="@style/button_rounded_colorized"
app:buttonText="@string/button_text_2"
app:buttonIco="@drawable/arrow"
/>
attrs.xml
<resources>
<declare-styleable name="IconifiedButton">
<attr name="buttonText" format="string" />
<attr name="buttonIco" format="integer" />
</declare-styleable>
</resources>
【问题讨论】:
标签: android android-layout android-button