You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过XML为AbstractComposeView设置属性值?

如何通过XML属性为AbstractComposeView封装的Composable设置值

要实现直接在XML里用app:titleText这类属性设置值,只需完成以下三步:

1. 创建自定义属性资源文件

在项目res/values目录下新建attrs.xml,定义需要的自定义属性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyComposeView">
        <attr name="titleText" format="string" />
    </declare-styleable>
</resources>

2. 在MyComposeView中解析XML属性

修改MyComposeView的构造函数,读取XML中设置的属性值并赋值给状态变量,同时处理默认值:

class MyComposeView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : AbstractComposeView(context, attrs, defStyleAttr) {

    private var titleText by mutableStateOf("Default text")

    var titleValue: String
        get() = titleText
        set(value) {
            titleText = value
        }

    init {
        attrs?.let {
            val typedArray = context.obtainStyledAttributes(it, R.styleable.MyComposeView)
            // 读取属性值,未设置则用默认文本
            titleText = typedArray.getString(R.styleable.MyComposeView_titleText) ?: "Default text"
            typedArray.recycle() // 务必回收TypedArray避免内存泄漏
        }
    }

    @Composable
    override fun Content() {
        ListItem(
            text = titleText,
        )
    }
}

@Composable
fun ListItem(
    text: String,
) {
    Row(
        modifier = Modifier,
    ) {
        Text(
            text = text,
        )
    }
}

3. 在XML布局中使用自定义属性

直接在MyComposeView标签里添加app:titleText属性,设置目标文本:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ViewActivity">

    <com.example.android.MyComposeView
        android:id="@+id/my_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:titleText="From XML Attribute"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

修改完成后,无需在Activity中编写赋值代码,XML中设置的app:titleText会直接生效。

内容的提问来源于stack exchange,提问作者Abhimanyu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 19:31:21