android_custom layout example

Why write a custom layout:

1. When implementing a large number of repeated sub-buttons or sub-layouts, if the workload of copying one by one is huge, you need to create a custom layout and import it directly into the layout, which can save a lot of time

Steps to create a custom layout:

1. Write a custom xml layout

2. Instantiate this custom xml layout into a Java layout class (inherit the layout class implementation), and add functions directly to the layout class

3. Write this class into the xml layout file of the parent class



Step 1: Write a custom xml layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <Button
        android:id="@+id/demobutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is an experimental button"/>

</LinearLayout>

Step 2: Instantiate this custom xml layout into a Java layout class (inherit the layout class implementation)

package com.example.prize.mydemo1;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
 * Created by prize on 2018/4/8.
 * Instantiate a custom layout and add button functions to the layout
 */

public class MyLayout extends LinearLayout {
    public MyLayout(Context context, AttributeSet attrs){
        super(context,attrs);
        LayoutInflater.from(context).inflate(R.layout.activity_mylayout,this); // Clip to instantiate mylayout layout
        Button button =(Button)findViewById(R.id.demobutton);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(),"Click to realize the test button",Toast.LENGTH_SHORT).show();
            }
        });

    }

}

Step 3: Write this class into the xml layout file of the parent class

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns: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">
    <!--Add custom layout-->
    <!--Note that the layout path requires all package name paths-->
    <com.example.prize.mydemo1.MyLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </com.example.prize.mydemo1.MyLayout>

</LinearLayout>

Realize the effect:



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325733966&siteId=291194637