我有一个这样的自定义视图。它实际上是一个自定义的constraintLayout(如果有关系)。可以是任何视图组:
class MyButtonView : ConstraintLayout {
constructor(p0: Context) : super(p0)
constructor(p0: Context, p1: AttributeSet?) : super(p0, p1)
constructor(p0: Context, p1: AttributeSet?, p2: Int) : super(p0, p1, p2)
init {
initView()
}
private fun initView() = inflate(context, R.layout.my_custom_view, this)
}
现在,my_custom_view.xml文件如下所示:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
android:id="@+id/cl_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:animateLayoutChanges="true"
tools:visibility="visible">
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#EFEFEF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.constraint.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="center"
android:text="@string/my_name"
android:textAppearance="@style/AsphaltTitleAndButtonTextStyle"
android:textColor="#555555"
android:textSize="14sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="RelativeOverlap,RtlHardcoded" />
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="4dp"
app:layout_constraintBottom_toBottomOf="@id/tv"
app:layout_constraintRight_toLeftOf="@id/tv"
app:layout_constraintTop_toTopOf="@id/tv"
app:srcCompat="@drawable/icon" />
</android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
现在看看我如何使用它:
<com.mypackage.example.MyButtonView
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="?attr/selectableItemBackground"
android:visibility="gone"
tools:visibility="visible" />
在运行时一切正常,所以我知道它的设置还可以。它仅在android studio 3.2.1预览窗口中,自定义视图不会显示预览。 它仅显示软件包名称。我怎样才能显示预览。到目前为止,这是我尝试过的:
class MyButtonView : ConstraintLayout {
constructor(p0: Context) : super(p0){initView()}
constructor(p0: Context, p1: AttributeSet?) : super(p0, p1){initView()}
constructor(p0: Context, p1: AttributeSet?, p2: Int) : super(p0, p1, p2){initView()}
init {
initView()
}
private fun initView() = inflate(context, R.layout.my_custom_view, this)
}