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會根據當前執行的平臺去載入正確的元件檔案