【Android、IOS、Flutter、鸿蒙、ReactNative 】标题栏

Android 标题栏 参考

Android Studio版本

配置gradle镜像 阿里云

Android使用 android:theme 显示标题栏

添加依赖

Dart 复制代码
dependencies {
    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.9.0")
   implementation("androidx.constraintlayout:constraintlayout:2.1.4")
}

配置 android:theme

Android 自定义标题栏

activity_main.xml布局文件配置ToolBar

Dart 复制代码
<androidx.appcompat.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    app:layout_constraintTop_toTopOf="parent"
    app:title="自定义 Toolbar"
    app:titleTextColor="@android:color/white" />

去除标题栏

android:theme="@style/Theme.AndroidAppBar" 主题设置后需要去除标题,不然主题标题栏和自定义标题栏同时存在。

Android自定义标题栏一

Dart 复制代码
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;

public class MainActivity extends AppCompatActivity {

    private final String TAG = this.getClass().getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //去除标题栏
        setContentView(R.layout.activity_main);
        initToolBar();
    }

    private void initToolBar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.drawable.back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "Toolbar Navigation Back");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.i(TAG, "onOptionsItemSelected " + item.getTitle().toString());
        int itemId = item.getItemId();
        if (itemId == R.id.menu_item1) {
            // 处理搜索按钮点击事件
            return true;
        } else if (itemId == R.id.menu_item2) {
            // 处理设置按钮点击事件
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}

Compose 标题栏 参考

build.gradle 添加依赖

Dart 复制代码
dependencies {
    ......
    implementation ("androidx.activity:activity-compose:1.3.1")
    implementation("androidx.compose.material:material:1.4.3")
    implementation("androidx.compose.ui:ui-tooling:1.4.3")
}

自定义标题栏

Dart 复制代码
package com.compose.appbar

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Menu
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview

class MainComposeActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent { topAppBar() }
    }
}

@Preview
@Composable
fun topAppBar() {
    Scaffold(topBar = {
        TopAppBar(title = { Text(text = "自定义标题栏") }, navigationIcon = {
            IconButton(
                onClick = { /*TODO*/ }) {
                Icon(Icons.Filled.ArrowBack, contentDescription = "Back")
            }
        }, actions = {
            IconButton(onClick = { /*TODO*/ }) {
                Icon(imageVector = Icons.Filled.Menu, contentDescription = "Menu")
            }
        }
        )
    }
    ) { innerPadding ->
        BodyContent1(Modifier.padding(innerPadding))
    }
}
@Composable
fun BodyContent1(padding: Modifier = Modifier) {

}

IOS Object-c 标题栏 参考

xcode版本

添加根视图控制器

在 SceneDelagate.m 里的如下函数添加根视图控制器:

Dart 复制代码
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {

    ViewController* root = [[ViewController alloc] init];
    UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:root];
    self.window.rootViewController = nav;
}

自定义标题、返回按钮、菜单按钮

系统默认图标

IOS Swift 标题栏 参考

添加根视图控制器

在 SceneDelagate.swift 里的如下函数添加根视图控制器:

自定义标题、返回按钮、菜单按钮

Flutter 标题栏

pubspec.yaml 里面配置 flutter_screenutil 依赖

Dart 复制代码
AppBar(
  backgroundColor: const Color(0xff6200EE),
  title: const Text(
    "自定义标题",
    style: TextStyle(color: Colors.white),
  ),
  leading: const Icon(
    Icons.arrow_back,
    color: Colors.white,
  ),
  actions: [
    Padding(
      padding: EdgeInsets.only(right: 20.w),
      child: const Icon(
        Icons.menu,
        color: Colors.white,
      ),
    )
  ],
)

鸿蒙 标题栏

Dart 复制代码
import router from '@ohos.router'
/**
 * TitleBar-标题栏
 */
@Preview
@Component
export default struct TitleBar {
  isShow: Boolean = true;//是否有返回按钮  默认:true
  title: string = '' //中间标题
  rightImg?: Resource;//右侧图标
  rightTxt: string = '';//右侧文字
  onRightTxtClick?: () => void;//右侧文字点击事件
  onRightImgClick?: () => void;//右侧图标点击事件

  build() {

    Stack() {
      Text(this.title)
        .textAlign(TextAlign.Center)
        .fontColor(Color.White)
        .maxLines(1)
        .fontSize('22fp')

      Row() {
        Image($r('app.media.ic_back'))
          .width('30vp')
          .height('30vp')
          .objectFit(ImageFit.Fill)
          .margin({ left: '10vp' })
          .onClick(() => {
            router.back()
          }).visibility(this.isShow ? Visibility.Visible : Visibility.Hidden)

        Text(this.rightTxt === '' ? '' : this.rightTxt)
          .height('20vp')
          .margin({ right: 20 })
          .fontSize('16fp')
          .fontColor($r('app.color.black'))
          .visibility(this.rightTxt === '' ? Visibility.None : Visibility.Visible)
          .onClick(()=>{
            this.onRightTxtClick!!();
          })

        Image(this.rightImg === undefined ? null : this.rightImg)
          .width('20vp')
          .height('20vp')
          .margin({ right: 20 })
          .visibility(this.rightImg === undefined ? Visibility.None : Visibility.Visible)
          .onClick(()=>{
            this.onRightImgClick!!();
          })
      }.width('100%').justifyContent(FlexAlign.SpaceBetween)
    }
    .width('100%')
    .height('60vp')
    .backgroundColor($r('app.color.color_6200EE'))
  }
}

React Native 标题栏

自定义 CustomTitleBar

Dart 复制代码
import React from 'react';
import { View, Text, StyleSheet, Image} from 'react-native';

const CustomTitleBar = ({ title,leftIcon,rightIcon}) => {
  return (
    <View style={styles.container}>
        <View style={styles.iconContainer}>
            <Image source={leftIcon} style={styles.icon} />
        </View>
        <View style={styles.titleBar}>
            <Text style={styles.title}>{title}</Text>
        </View>
        <View style={styles.iconContainer}>
              <Image source={rightIcon} style={styles.icon} />
         </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '100%',
    backgroundColor: '#6200EE',
  },
  iconContainer: {
    padding: 10,
  },
  icon: {
      width: 30,
      height: 30,
      resizeMode: 'contain'
  },
  titleBar: {
    height: 60,
    justifyContent: 'center',
    alignItems: 'center',
    flex:1
  },
  title: {
    color: 'white',
    fontSize: 20,
    fontWeight: 'bold',
  },
});

export default CustomTitleBar;

显示标题栏

Dart 复制代码
import {AppRegistry} from 'react-native';
import {name as appName} from './app.json';

import React from 'react';
import { View, Text } from 'react-native';
import CustomTitleBar from './CustomTitleBar';

const MyApp = () => {
  return (
    <View style={{ flex: 1 }}>
      <CustomTitleBar title="我的标题"
       leftIcon={require('./assets/ic_back.png')}
        rightIcon={require('./assets/ic_menu.png')}/>
    </View>
  );
};

AppRegistry.registerComponent(appName, () => MyApp);

Cannot find module 'react-scripts/package.json'

Dart 复制代码
执行如下命令:
 
npm install

运行到安卓平台

采用 npx react-native run-androidnpm start 运行

案例

所属分支

相关推荐
m0_7482478037 分钟前
Flutter Intl包使用指南:实现国际化和本地化
前端·javascript·flutter
Code&Ocean1 小时前
iOS从Matter的设备认证证书中获取VID和PID
ios·matter·chip
/**书香门第*/1 小时前
Laya ios接入goole广告,开始接入 2
ios
迷雾漫步者2 小时前
Flutter组件————PageView
flutter·跨平台·dart
迷雾漫步者9 小时前
Flutter组件————FloatingActionButton
前端·flutter·dart
拭心11 小时前
Google 提供的 Android 端上大模型组件:MediaPipe LLM 介绍
android
带电的小王14 小时前
WhisperKit: Android 端测试 Whisper -- Android手机(Qualcomm GPU)部署音频大模型
android·智能手机·whisper·qualcomm
coder_pig14 小时前
📝小记:Ubuntu 部署 Jenkins 打包 Flutter APK
flutter·ubuntu·jenkins
梦想平凡14 小时前
PHP 微信棋牌开发全解析:高级教程
android·数据库·oracle
元争栈道14 小时前
webview和H5来实现的android短视频(短剧)音视频播放依赖控件
android·音视频