简体   繁体   中英

How to android inflate XML Layout in ConstraintLayout class?

i create a ConstrantLayout class

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 file to inflate into class

Create layout how you want your custom view to look like. There is nothing complicated about it.

<?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>

This way you can set constraints and edit the layout with editor.

AFTER you are done with editting I would recommend changing the root view ConstraintLayout to merge .

By merging you won't have extra layout inside the custom view. Be careful - merge attributes are ignored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM