我正在尝试创建一个自定义视图组,以使子级进入特定的布局。我试图覆盖addview方法,但是遇到了几个不同的错误。我的布局和相应的代码如下。因此,请问如何在llContent(LinearLayout)下添加视图。
因此,在创建布局后,我需要在xml的llContent下添加任何视图或addView方法。
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp">
<TextView
android:id="@+id/txtError"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/rounded_negative"
android:gravity="center_horizontal"
android:paddingBottom="10dp"
android:textColor="@color/white"
android:translationY="60dp"
app:layout_constraintBottom_toTopOf="@+id/clContent"
tools:text="error" />
<com.github.florent37.shapeofview.shapes.RoundRectView
android:id="@+id/clContent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/txtError"
app:shape_roundRect_borderColor="@color/borderColor"
app:shape_roundRect_borderWidth="@dimen/borderWidth"
app:shape_roundRect_bottomLeftRadius="@dimen/borderRadius"
app:shape_roundRect_bottomRightRadius="@dimen/borderRadius"
app:shape_roundRect_topLeftRadius="@dimen/borderRadius"
app:shape_roundRect_topRightRadius="@dimen/borderRadius">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white" />
**<LinearLayout
android:id="@+id/llContent"
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical">
</LinearLayout>**
</com.github.florent37.shapeofview.shapes.RoundRectView>
</androidx.constraintlayout.widget.ConstraintLayout>
</FrameLayout>
</merge>
class CustomView: FrameLayout {
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { init(attrs)}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(attrs)}
private fun init(attrs: AttributeSet) {
LayoutInflater.from(context).inflate(R.layout.custom_view, this, true)
parseAttributes(attrs)
}
private fun parseAttributes(attrs: AttributeSet) {
/*
TODO
val values = context.obtainStyledAttributes(attrs, R.styleable.CustomView)
values.recycle()
*/
}
override fun addView(child: View?, index: Int) {
if (child == null) {
throw IllegalArgumentException("Cannot add a null child view to a ViewGroup")
}
var params: FrameLayout.LayoutParams? = child.layoutParams as LayoutParams
if (params == null) {
params = generateDefaultLayoutParams()
if (params == null) {
throw IllegalArgumentException("generateDefaultLayoutParams() cannot return null")
}
}
addView(child, index, params)
}