Android 从自定义布局中的子视图读取自定义布局属性
我创建了自己的布局。我定义了一个“good”属性用于其子视图Android 从自定义布局中的子视图读取自定义布局属性,android,android-layout,android-layoutparams,Android,Android Layout,Android Layoutparams,我创建了自己的布局。我定义了一个“good”属性用于其子视图 <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyLayout"> <attr name="good" format="boolean" /> </declare-styleable> </resources> 现在我想从孩子
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyLayout">
<attr name="good" format="boolean" />
</declare-styleable>
</resources>
现在我想从孩子们那里读这个属性。但是怎么做呢?我在网上搜索过,尝试过一些东西,但似乎不起作用
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()
}
}
}
}
您应该在
MyLayout
中使用自定义LayoutParams
-查看FrameLayout
、LinearLayout
、RelativeLayout
等中使用了哪些LayoutParams
,
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()
}
}
}
}