Android 自定义布局和自定义控件的简单使用

一. 自定义布局的简单使用

  1. 建立一个自定义布局
    在这里插入图片描述
  2. 在你要使用自定义布局的活动中引用
    在这里插入图片描述
    3.隐藏原标题栏
 @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
    
    
            actionBar.hide();
        }
    }

在这里插入图片描述
二. 自定义布局的控件使用

  1. 引用时设置ID

在这里插入图片描述

2.使用

  android.support.constraint.ConstraintLayout constraintLayout;// android.support.constraint.ConstraintLayout 你现在使用的布局
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
    
    
            actionBar.hide();
        }
        constraintLayout=findViewById(R.id.layout_include);
        Button button=constraintLayout.findViewById(R.id.button6);
        button.setOnClickListener(new View.OnClickListener(){
    
    
            @Override
            public void onClick(View v) {
    
    
                Toast.makeText(MainActivity.this, "退出", Toast.LENGTH_SHORT).show();
            }
        });
    }

三. 自定控件的简单使用
用于解决作用重复使用的控件,如标题栏的退出按钮
1.新建一个类,继承你的自定义按钮的布局,重写TitleLayout方法(两个参数的)

package com.example.lzz.myapplication;

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

public class TitleLayout extends android.support.constraint.ConstraintLayout {
    
    
    public TitleLayout(final Context context, AttributeSet attrs) {
    
    
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.layout_title,this);
        Button button=findViewById(R.id.button6);
        button.setOnClickListener(new View.OnClickListener(){
    
    
            @Override
            public void onClick(View v) {
    
    
                Toast.makeText(context, "退出", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

2.在布局中引用

<com.example.lzz.myapplication.TitleLayout android:layout_width="match_parent" android:layout_height="wrap_content">

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/LiuxXn/article/details/106634010
今日推荐