zoukankan      html  css  js  c++  java
  • android_自定义布局例子

    为什么要写自定义布局:

    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>


  • 相关阅读:
    Python 用SMTP发送邮件
    Python 用IMAP接收邮件
    E-mail Composition and Decoding
    用Python实现gmail邮箱服务,实现两个邮箱之间的绑定(中)
    【日志】-2013.10.31
    21本计算机数学相关的免费电子书【转】
    WordPress搭建Personal Blog【转】
    一句话点亮你的人生
    【日志】-2013.10.28
    转载-smarty教程(基本语法)
  • 原文地址:https://www.cnblogs.com/guanxinjing/p/9708637.html
Copyright © 2011-2022 走看看