Java 如何在ConstraintLayout类中扩展XML布局?

Java 如何在ConstraintLayout类中扩展XML布局?,java,android,layout-inflater,android-constraintlayout,Java,Android,Layout Inflater,Android Constraintlayout,我创建了一个ConstantLayout类 public class AboutView extends ConstraintLayout { TextView about_txt; TextView dr_txt; public AboutView(Context context) { super( context ); init(); } public AboutView(Context context, Attr

我创建了一个ConstantLayout类

public class AboutView extends ConstraintLayout {

    TextView about_txt;
    TextView dr_txt;

    public AboutView(Context context) {
        super( context );
        init();
    }

    public AboutView(Context context, AttributeSet attrs, int defStyleAttr) {
        super( context, attrs, defStyleAttr );
        init();
    }

    private void init() {
        LayoutInflater inflater = LayoutInflater.from( getContext() );
        inflater.inflate( R.layout.about_layout,this );

        about_txt = (TextView) findViewById(R.id.about_txt);
        dr_txt = (TextView) findViewById(R.id.dr_txt);
    }

}

Layout about_Layout.XML文件以充气到类中

创建自定义视图的布局。这并不复杂

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools">

    <TextView
        android:id="@+id/about_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        app:layout_constraintStart_toStartOf="parent"
        tools:text="About" />

    <TextView
        android:id="@+id/dr_txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        tools:text="Text" />

</android.support.constraint.ConstraintLayout>

这样,您可以设置约束并使用编辑器编辑布局

编辑完成后,我建议将根视图ConstraintLayout更改为merge

通过合并,在自定义视图中不会有额外的布局。小心-合并属性被忽略