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,这里可以换成你想要的任何操作
             }
         });

    }

开机打包运行,一切正常

相关推荐
一笑的小酒馆2 小时前
Android中的tcp通信
android
默阳12345 小时前
2026年Android中高级面试题专栏(Android进阶篇)
android
古法安卓5 小时前
Android-日志系统源码解析
android·java·android studio
恋猫de小郭6 小时前
Android 17 + OkHttp 5.5.0 ,全新 ECH 下你的 HTTPS 域名可以请求时被安全隐藏
android·前端·flutter
小强闯江湖6 小时前
不只是让 AI 写代码:ViewCompose 把 Android UI 做成了可编译、可渲染的闭环
android·人工智能·kotlin
hunterandroid8 小时前
StateFlow 与 SharedFlow 的边界:状态与事件的正确建模
android·前端
YF02118 小时前
Android遥控器对频详解
android·android things
码农coding9 小时前
android12 WindowManagerService窗口的布局过程
android·源码
杉氧12 小时前
状态管理变迁史:为什么我们放弃了 Redux 选择 Zustand?
android·前端·react native
三少爷的鞋15 小时前
别再靠 Code Review 守底线:我做了一个静态分析项目 RedLine
android