观心静

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
  422 随笔 :: 0 文章 :: 86 评论 :: 139万 阅读

为什么要写自定义布局:

1.在实现大量重复的子按键或者子布局时,如果一个一个去复写工作量庞大,就需要创建自定义布局直接导入布局里,可以节省大量的时间

创建自定义布局的步骤:

1.编写一个自定义xml布局

2.将这个自定义xml布局实例化成Java布局类(继承布局类实现),在布局类中直接添加功能

3.将这个类写入父类的xml布局文件里

 

步骤1:编写一个自定义xml布局

复制代码
<?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="这是一个实验按键"/>

</LinearLayout>
复制代码

 

 

步骤2:将这个自定义xml布局实例化成Java布局类(继承布局类实现)

复制代码
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.
 * 实例化一个自定义布局,并且在布局中添加按键功能
 */

public class MyLayout extends LinearLayout {
    public MyLayout(Context context, AttributeSet attrs){
        super(context,attrs);
        LayoutInflater.from(context).inflate(R.layout.activity_mylayout,this); //剪裁实例化mylayout布局
        Button button =(Button)findViewById(R.id.demobutton);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getContext(),"点击实现了试验按键",Toast.LENGTH_SHORT).show();
            }
        });

    }

}
复制代码

步骤3:将这个类写入父类的xml布局文件里

复制代码
<?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">
    <!--添加自定义布局-->
    <!--注意布局路径是需要全部包名路径-->
    <com.example.prize.mydemo1.MyLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </com.example.prize.mydemo1.MyLayout>

</LinearLayout>
复制代码


posted on   观心静  阅读(3062)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示