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

本文详细介绍如何在Android应用中创建并使用自定义布局及控件,包括隐藏默认标题栏、在布局中引用自定义控件及实现重复使用控件的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值