【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 运行

案例

所属分支

相关推荐
深海呐21 分钟前
Android 最新的AndroidStudio引入依赖失败如何解决?如:Failed to resolve:xxxx
android·failed to res·failed to·failed to resol·failed to reso
解压专家66623 分钟前
安卓解压软件推荐:高效处理压缩文件的实用工具
android·智能手机·winrar·7-zip
Rverdoser24 分钟前
Android 老项目适配 Compose 混合开发
android
q567315232 小时前
用 PHP或Python加密字符串,用iOS解密
java·python·ios·缓存·php·命令模式
Hgc558886662 小时前
iOS 18.2 重磅更新:6个大动作
ios
努力遇见美好的生活3 小时前
Mysql每日一题(行程与用户,困难※)
android·数据库·mysql
lrlianmengba4 小时前
推荐一款好用的ios传输设备管理工具:AnyTrans for iOS
macos·ios·cocoa
图王大胜5 小时前
Android Framework AMS(17)APP 异常Crash处理流程解读
android·app·异常处理·ams·crash·binderdied·讣告
ch_s_t5 小时前
电子商务网站之首页设计
android