Android自定义布局

TextView居中:

android:layout_gravity="center"
android:gravity="center"

添加布局:

<?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="wrap_content">

    <ImageButton
        android:layout_width="0sp"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/ret"
        android:layout_weight="1"
        android:id="@+id/btnRet" />

    <TextView
        android:text="标题"
        android:layout_width="0sp"
        android:layout_height="match_parent"
        android:id="@+id/textView"
        android:layout_weight="3"
        android:layout_gravity="center"
        android:gravity="center"
        android:textSize="35sp" />

    <ImageButton
        android:layout_width="0sp"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/edit"
        android:layout_weight="1"
        android:id="@+id/btnEdt" />
</LinearLayout>

可以在任意Activaty将自定义布局添加进来:

    <com.example.admin.testproj.TitleLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/title">
    </com.example.admin.testproj.TitleLayout>

在代码TitleLayout中,继承自LinearLayout并实现按钮点击之后的回调:

package com.example.admin.testproj;

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

public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs){
        super(context,attrs);
        LayoutInflater.from(context).inflate(R.layout.title,this);
        findViewById(R.id.btnRet).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                ((Activity)getContext()).finish();
            }
        });
        findViewById(R.id.btnEdt).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(),"点击了编辑按钮",Toast.LENGTH_SHORT).show();
            }
        });
    }
}

界面:
在这里插入图片描述
如果只是界面的显示的话,layout做好后可在别的layout中使用include添加进来:

<include layout="@layout/login"/>

代码:https://github.com/yangyang0312/AndroidTestCode/tree/master/TestProj

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值