3

独自のレイアウトを作成しました。そして、その子ビューに使用する「良い」属性を定義しました。

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

属性はこのように使用されます。android:layout_centerInParentの子ビューに使用できるようなものですが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>

今、私はその属性を子から読みたいと思っています。しかし、どのように?Web を検索していくつかのことを試しましたが、うまくいかないようです。

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