如何在Android中使用CustomView



在我的应用程序中,我为showTextViewFontAwesome创建了一个自定义视图
我编写以下代码,但不设置值,只显示默认值
TextWithIcon类:

class TextWithIcon @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
defStyleRes: Int = 0
) : LinearLayout(context, attrs, defStyle, defStyleRes) {
init {
LayoutInflater.from(context).inflate(R.layout.layout_text_with_awesome, this, true)
orientation = VERTICAL
attrs?.let {
val typedArray = context.obtainStyledAttributes(R.styleable.TextWithIcon)
val title = resources.getText(
typedArray.getResourceId(
R.styleable.TextWithIcon_customText,
R.string.app_name
)
)
val icon = resources.getText(
typedArray.getResourceId(
R.styleable.TextWithIcon_customIcon,
R.string.app_name
)
)
val titleTxt = getChildAt(0) as TextView
titleTxt.text = title
Log.e("titleTxt",title.toString())
//binding.iconTxt.text = "&#x$icon"
typedArray.recycle()
}
}
}

CustomViewLayout文件:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="@+id/titleTxt"
android:layout_width="wrap_content"
android:layout_height="@dimen/_20mdp"
android:gravity="right"
android:textColor="@color/darkJungleGreen"
android:textSize="@dimen/_10font_mdp" />
<com.myapp.utils.views.FontAwesome
android:id="@+id/iconTxt"
android:layout_width="@dimen/_20mdp"
android:layout_height="@dimen/_20mdp"
android:layout_gravity="right"
android:gravity="center"
android:textColor="@color/beauBlue"
android:textSize="@dimen/_10font_mdp"
app:fontPath="fonts/fontawesome_re.ttf" />
</merge>

我将这个类与XML中的代码一起使用:

<com.myapp.TextWithIcon
android:id="@+id/item1Title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="@dimen/_10mdp"
android:drawablePadding="@dimen/_5mdp"
android:gravity="center"
android:textColor="@color/ochre"
android:textSize="@dimen/_10font_mdp"
app:customIcon="f007"
app:customText="wegwergewrg"
app:fontPath="fonts/iransans_bold.ttf"
app:layout_constraintEnd_toStartOf="@id/item1Line"
app:layout_constraintTop_toTopOf="@id/item1Line" />

我用这个代码设置值:app:customText="wegwergewrg",但不显示这个,只显示的默认值

resources.getText(
typedArray.getResourceId(
R.styleable.TextWithIcon_customText,
R.string.app_name
)
)

我该怎么修?

您将希望您的样式表看起来像这样:

<resources>
<declare-styleable name="TextWithIcon">
<attr name="customText" format="reference|string" />
</declare-styleable>
</resources>

这个定义将允许您使用文本以及字符串资源id作为";app:customText";。

您可以从属性中获得如下值:

class TestCustomView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : androidx.appcompat.widget.AppCompatTextView(context, attrs) {
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.TextWithIcon)
for (attr in 0 until a.indexCount) {
when (a.getIndex(attr)) {
R.styleable.TextWithIcon_customText -> {
text = a.getText(attr) ?: "Unknown text."
}
}
}
a.recycle()
}
}

相关内容

  • 没有找到相关文章

最新更新