Android顶部标题栏自定义,添加按钮

  1. 先写一个标题栏的layout, 放在工程的res/layout下,如下:

    <?xml version="1.0" encoding="utf-8"?>

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">

    复制代码
     <TextView
         android:id="@+id/tv_title"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentLeft="true"
         android:layout_marginLeft = "10dp"
         android:text = "AgoraVideo"
         android:textAppearance="?android:attr/textAppearanceLarge"
         />
    
     <Button
         android:id="@+id/return_btn"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignParentEnd="true"
         android:layout_marginEnd="10dp"
         android:text = "返回"  />
    </RelativeLayout>

这个标题栏里就一个文本代表标题,靠左对齐离最左边10dp,还有个返回按钮靠右对齐,离最右边10个dp

  1. 在你的MainActivity里onCreate方法里就可以用它了

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_agora_test); //主程序的UI layout

    复制代码
         //设置自定义标题栏
         getSupportActionBar().setDisplayShowCustomEnabled(true);
         //从资源中取出这个自定义标题栏
          View actionBar = LayoutInflater.from(this).inflate(R.layout.custom_action_bar, null);
         //设置对齐参数
         ActionBar.LayoutParams params = new         ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
         //设置为自定义标题栏
         getSupportActionBar().setCustomView(actionBar, params);
    
         //取出标题栏里的返回按钮
         Button btnReturn = actionBar.findViewById(R.id.return_btn);
         btnReturn.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 finish(); //这个是返回上个Activity,这里可以换成你想要的任何操作
             }
         });

    }

开机打包运行,一切正常

相关推荐
一条上岸小咸鱼1 小时前
Kotlin 基本数据类型(一):Numbers
android·前端·kotlin
Huntto2 小时前
最小二乘法计算触摸事件速度
android·最小二乘法·触摸事件·速度估计
一笑的小酒馆2 小时前
Android中使用Compose实现各种样式Dialog
android
红橙Darren2 小时前
手写操作系统 - 编译链接与运行
android·ios·客户端
鹏多多.6 小时前
flutter-使用device_info_plus获取手机设备信息完整指南
android·前端·flutter·ios·数据分析·前端框架
来来走走11 小时前
Flutter开发 网络请求
android·flutter
独行soc17 小时前
2025年渗透测试面试题总结-18(题目+回答)
android·python·科技·面试·职场和发展·渗透测试
雨白18 小时前
登录和授权:Cookie与Authorization Header机制详解
android
Frank_HarmonyOS18 小时前
【Android -- 多线程】Handler 消息机制
android
一条上岸小咸鱼19 小时前
Kotlin 基本数据类型(一):概述及分类
android·kotlin