react native学习笔记22——常用API(4)ToastAndroid、BackHandler及特定平台代码常用写法

前言

前面三节中介绍的React Native官方提供的api都是双平台通用的api,在React Native中也有一些只在特定平台才能使用的api,官方的命名也很友善,只适用于Android的api通常叫XXXAndroid,同理只使用于iOS的通常叫XXXIOS,例如今天将介绍的ToastAndroid。但也有例外,例如BackHandler,只适用于Android平台,用于返回键处理的api,在rn0.45版本之前是BackAndroid,0.45以后废弃了BackAndroid。新的API——BackHandler和旧API——BackAndroid用法是一致的,只是新的API增加了对tvOS的支持。

ToastAndroid

用于在Android设备上显示一个悬浮的提示信息,通常用于弱信息提醒,该提醒不会影响用户交互。

方法

static show(message:string,duration:number) 设置toast消息的弹出

static showWithGravity(message:string, duration:number, gravity:number) 设置toast消息的弹出,可以设置toast的位置。

属性

  • SHORT 静态int值,表示toast显示较短的时间
  • LONG 静态int值,表示otast显示较长的时间
  • TOP 静态int值,toast顶部显示
  • BOTTOM 静态int值,toast底部显示
  • CENTER 静态int值,toast中间显示

使用实例

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ToastAndroid,
    TouchableHighlight
} from 'react-native';

export default class ToastAndroidDemo extends Component {
    render() {
        return (
            <View>

                <TouchableHighlight
                    style={styles.button}
                    underlayColor="#a5a5a5"
                    onPress={()=>ToastAndroid.show('长时间的toast',ToastAndroid.LONG)}>
                    <Text style={styles.buttonText}>长时间toast</Text>
                </TouchableHighlight>
                <TouchableHighlight
                    style={styles.button}
                    underlayColor="#a5a5a5"
                    onPress={()=>ToastAndroid.show('短时间的toast',ToastAndroid.SHORT)}>
                    <Text style={styles.buttonText}>短时间toast</Text>
                </TouchableHighlight>
                <TouchableHighlight
                    style={styles.button}
                    underlayColor="#a5a5a5"
                    onPress={()=>ToastAndroid.showWithGravity('top toast',ToastAndroid.SHORT,ToastAndroid.TOP)}>
                    <Text style={styles.buttonText}>top toast</Text>
                </TouchableHighlight>
                <TouchableHighlight
                    style={styles.button}
                    underlayColor="#a5a5a5"
                    onPress={()=>ToastAndroid.showWithGravity('center toast',ToastAndroid.SHORT,ToastAndroid.CENTER)}>
                    <Text style={styles.buttonText}>center toast</Text>
                </TouchableHighlight>
                <TouchableHighlight
                    style={styles.button}
                    underlayColor="#a5a5a5"
                    onPress={()=>ToastAndroid.showWithGravity('bottom toast',ToastAndroid.SHORT,ToastAndroid.BOTTOM)}>
                    <Text style={styles.buttonText}>bottom toast</Text>
                </TouchableHighlight>
            </View>
        );
    }
}
const styles = StyleSheet.create({
    button: {
        margin:5,
        backgroundColor: 'white',
        padding: 15,
        borderWidth: StyleSheet.hairlineWidth,
        borderColor: '#cdcdcd',
    }
});

BackHandler

监听设备上的返回按钮事件。

  • Android:监听后退按钮事件。如果没有添加任何监听函数,或者所有的监听函数都返回false,则会执行默认行为,退出应用。
  • tvOS(即Apple TV机顶盒):监听遥控器上的后退按钮事件(阻止应用退出的功能尚未实现)。

监听函数是按倒序的顺序执行(即后添加的函数先执行)。如果某一个函数返回true,则后续的函数都不会被调用。

方法

static exitApp() 退出应用

static addEventListener(eventName:BackPressEventName,handler:Function) 添加back返回键监听事件

static removeEventListener(eventName:BackPressEventName,handler:Function) 删除back返回键监听事件

使用实例

import React, { Component } from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    View,
    ToastAndroid,
    Platform,
    BackHandler,
} from 'react-native';
let count=2;
export default class BackHandlerDemo extends Component {
    componentDidMount(){
        if (Platform.OS === 'android') {
            BackHandler.addEventListener('hardwareBackPress', function () {
                if (count >= 1) {
                    ToastAndroid.show('收到点击返回键信息...' + count, ToastAndroid.SHORT);
                    count--;
                    return true;
                } else {
                    return false;
                }
            });
        }
    }
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.instructions}>
                    请点击返回键查看效果...
                </Text>
            </View>
        );
    }
    componentWillUnmount() {
        if (Platform.OS === 'android') {
            BackHandler.removeEventListener('hardwareBackPress',()=>{});
        }
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    welcome: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
    instructions: {
        textAlign: 'center',
        color: '#333333',
        marginBottom: 5,
    },
});

在上述示例中我们使用了形如if (Platform.OS === 'android') {...}的判断语句,该判断语句的作用是区分平台,让返回监听事件只在Android平台上执行,在ios中则不执行里面的逻辑。这是Android,iOS双平台开发时特殊代码的相关写法之一。下面总结了在构建开发跨平台app时,针对不同的平台需求编写不同的代码的方法。

特定平台代码常用写法

检测平台

React Native提供了检测客户端当前运行的平台的模块,该模块在小范围的平台定制代码中很有用,如上面BackHandler的实例。

import {   Platform  } from 'react-native';
if (Platform.OS === 'android') { 
...
}
if (Platform.OS === 'ios') { 
...
}

一个实用的方法是Platform.select(),通过前面的Platform.OS的值针对不同平台使用不同的组件或不同的布局样式,见下面的示例:

import { Platform, StyleSheet } from 'react-native';

var styles = StyleSheet.create({
  container: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
    }),
  },
});

上面的代码会根据平台的不同返回不同的container样式——iOS上背景色为红色,而android为蓝色。

这一方法可以接受任何合法类型的参数,因此你也可以直接用它针对不同平台返回不同的组件,像下面这样:

var Component = Platform.select({
  ios: () => require('ComponentIOS'),
  android: () => require('ComponentAndroid'),
})();
<Component />;
检测平台版本

在Android上,Version属性是一个数字,表示Android的api level:

import { Platform } from 'react-native';

if(Platform.Version === 21){
  console.log('Running on Lollipop!');
}

在iOS上,Version属性是-[UIDevice systemVersion]的返回值,具体形式为一个表示当前系统版本的字符串。比如可能是”10.3”。

文件管理

即把针对不同平台的组件放置到不同的文件夹下管理。如:

/common/components/   
/android/components/   
/ios/components/

该方法是最直接的方法。
另一种类似的处理方法是根据平台不同在文件命名上进行区分。如:

MyButtonIOS.js
MyButtonAndroid.js

特定平台扩展名

React Native会检测某个文件是否具有.ios.或是.android.的扩展名,然后根据当前的平台加载对应的文件。

假设你的项目中有如下两个文件:

MyButton.ios.js
MyButton.android.js

以这样的方式命名组件后,你可以在其他组件中直接引用,而无需关心当前运行的平台环境。具体使用方式如下:

import MyButton from './components/MyButton';

React Native会根据当前运行的平台去加载正确的组件文件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值