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

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

    复制代码
     <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 = "返回"  />

这个标题栏里就一个文本代表标题,靠左对齐离最左边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,这里可以换成你想要的任何操作
             }
         });

    }

开机打包运行,一切正常

相关推荐
三少爷的鞋6 小时前
Java 线程自上而下,Kotlin 协程自下而上
android
好的佩奇7 小时前
Dart 之增强枚举
android·flutter·dart
梦影_8 小时前
MySQL进阶教程(五)—— SQL调优(下)
android·大数据·数据库·后端·sql·mysql·database
好的佩奇10 小时前
蓝牙之无线电与通信距离
android·flutter·蓝牙
vilya10 小时前
我把一套完整的 Python Agent 运行时塞进手机 APK:依赖闭包、Rust 轮子和三个真机坑
android
呆呆敲代码的小Y12 小时前
【实战精选面试题】C# 面试题详细解答,按难易程度排序
android·java·游戏·c#·游戏开发·unity面试题·c#面试题
思想觉悟14 小时前
SEAndroid实战
android·linux·c++
思想觉悟14 小时前
Aosp开发磨刀石之ADB速查
android·c++
应用市场17 小时前
用本机跑的开源音乐模型,给安卓小游戏做 20 秒无缝循环背景音乐
android·python·游戏开发·soundpool·音频处理
企业数字化笔记17 小时前
表单发布前怎么验收?版本引用、字段兼容和历史数据回归
android·数据挖掘·回归