3

我创建了自己的布局。我定义了一个“好”属性用于其子视图。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyLayout">
        <attr name="good" format="boolean" />
    </declare-styleable>
</resources>

属性是这样使用的。这有点像您可以android:layout_centerInParent用于 a 的子视图RelativeLayout,尽管我不确定为什么我的应该以“app:”开头,而以“android:”开头。

<?xml version="1.0" encoding="utf-8"?>
<com.loser.mylayouttest.MyLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <Button
        app:good = "true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</com.loser.mylayouttest.MyLayout>

现在我想从孩子那里读到那个属性。但是怎么做?我在网上搜索并尝试了一些东西,但似乎没有用。

class MyLayout: LinearLayout
{
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
    {
        setMeasuredDimension(200, 300); // dummy

        for(index in 0 until childCount)
        {
            val child = getChildAt(index);
            val aa = child.context.theme.obtainStyledAttributes(R.styleable.MyLayout);
            val good = aa.getBoolean(R.styleable.MyLayout_good, false)
            aa.recycle();
            Log.d("so", "value = $good")
        }
    }
}

补充:在评论的提示下,我找到了这个文档,并修改了我的代码,如下所示,现在我得到了我想要的结果。

class MyLayout: LinearLayout
{
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
    {
        setMeasuredDimension(200, 300);

        for(index in 0 until childCount)
        {
            val child = getChildAt(index);
            val p = child.layoutParams as MyLayoutParams;
            Log.d("so", "value = ${p.good}")

        }
    }

    override fun generateDefaultLayoutParams(): LayoutParams
    {
        return MyLayoutParams(context, null);
    }

    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams
    {
        return MyLayoutParams(context, attrs);
    }

    override fun checkLayoutParams(p: ViewGroup.LayoutParams?): Boolean
    {
        return super.checkLayoutParams(p)
    }

    inner class MyLayoutParams: LayoutParams
    {
        var good:Boolean = false;
        constructor(c: Context?, attrs: AttributeSet?) : super(c, attrs)
        {
            if(c!=null && attrs!=null)
            {
                val a = c.obtainStyledAttributes(attrs, R.styleable.MyLayout);
                good = a.getBoolean(R.styleable.MyLayout_good, false)
                a.recycle()
            }
        }
    }
}
4

0 回答 0