編輯:關於 Android 程式設計
原生應用並非只能整屏跳轉到 RN 頁面,也可以把 RN 組件當作一個普通控件嵌進原生界面,成為其中的一部分。本文記錄完整的接入過程,以及一路上遇到的各類報錯與解法。
用 Android Studio 新建項目(本文示例名為 RnInAndroid),然後打開命令行終端進入項目根目錄。
執行:
npm init
會生成 package.json,也就是 RN 的配置文件,過程中按需填寫信息。

輸入 yes 確認後,安裝 RN 依賴:
npm install --save react react-native
這會联网下載 node_modules 組件庫。接著下載 flow 配置:
curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
打開剛生成的 package.json,在 "scripts" 裡 "test" 那一行末尾補一個逗號(JSON 格式要求),然後新增啟動腳本:
"start": "node node_modules/react-native/local-cli/cli.js start"

在項目根目錄新建 index.android.js,寫入一個最簡單的 RN 頁面(Text 組件相當於 Android 的 TextView):
'use strict';
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class HelloWorld extends React.Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.hello}>這就是 RN 的頁面哦</Text>
<Text style={styles.hello}>我是劉成</Text>
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
hello: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
打開 app/build.gradle,在 dependencies 塊中加入:
compile "com.facebook.react:react-native:+"
再打開項目根目錄的 build.gradle(注意這是另一個文件),在 allprojects 下的 repositories 中新增 maven 源:
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}

在 app/src/main/AndroidManifest.xml 的 manifest 標籤內、與 application 同級處加入:
<uses-permission android:name="android.permission.INTERNET" />
在項目包路徑下新建 MyReactActivity.java:
package com.example.vittorio.rninandroid;
import android.app.Activity;
import android.os.Bundle;
import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
/**
* Created by vittorio on 2016/10/14.
*/
public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);
setContentView(mReactRootView);
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
}
幾點注意:
若出現如下錯誤:
Error: Conflict with dependency 'com.google.code.findbugs:jsr305'. Resolved versions for app (3.0.0) and test app (2.0.1) differ.

在根目錄 build.gradle 的 android 代碼塊中加入:
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.0'
}

之後 Build > Rebuild Project 重新編譯。
在 AndroidManifest.xml 中注册 MyReactActivity,並為它指定一個主題(例如 Theme.AppCompat.Light.NoActionBar,避免標題欄遮擋)。
在 MyReactActivity 中補上生命週期方法:
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onResume(this, this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onDestroy();
}
}
// 把返回鍵事件交給 React Native 處理
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
默認情況下搖一搖設備才能調出調試菜單,模擬器上不方便,因此還要攔截菜單鍵(Android Studio 模擬器按 Ctrl + M 可觸發):
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
在 MainActivity 的布局中加一個按鈕,點擊後跳轉到 MyReactActivity。

在命令行啟動 Node 服務:
npm start
打開模擬器(筆者用 Genymotion,你也可以用 AS 自帶模擬器或真機),點擊 Run。
E/AndroidRuntime: FATAL EXCEPTION: main android.view.WindowManager$BadTokenException: Unable to add window -- permission denied for window type 2003
解法是補上懸浮窗相關權限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
java.lang.IllegalAccessError: Method 'void android.support.v4.net.ConnectivityManagerCompat.<init>()' is inaccessible to class 'com.facebook.react.modules.netinfo.NetInfoModule'
這在 RN 社區也有大量報告。解法是調整三處配置:

原因是 maven 的 url 路徑寫錯了。$rootDir 本身就指向項目根目錄,多寫一層 ../ 會找不到 node_modules:
maven {
url "$rootDir/node_modules/react-native/android"
}
Error:(52, 34) 錯誤: 找不到符號 符號: 方法 onPause() 位置: 類型為ReactInstanceManager的變量 mReactInstanceManager
這通常是 RN 版本與接入方式不匹配導致的。筆者當時的解法是把這三個方法註釋掉,編譯即可通過。

在 AndroidManifest.xml 中為該 Activity 補齊相應配置即可恢復。
注意 MyReactActivity 裡其實就是一句 setContentView(mReactRootView)。也就是說,只要把 mReactRootView 塞進任意一個普通布局容器,RN 就變成了一個控件。
做法一:代碼中 addView
新建 myreactactivity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:background="#6638"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="200dp"
android:text="上半部分是 android 的布局"
android:textSize="30sp" />
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);
setContentView(R.layout.myreactactivity);
initView();
}
private void initView() {
ll = (LinearLayout) findViewById(R.id.ll);
ll.addView(mReactRootView);
}
做法二:直接在 XML 中聲明 ReactRootView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:background="#6638"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="200dp"
android:text="上半部分是 android 的布局"
android:textSize="30sp">
<com.facebook.react.ReactRootView
android:id="@+id/rnview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</TextView>
</LinearLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myreactactivity);
// 已在布局中聲明,無需 new,直接取出即可
mReactRootView = (ReactRootView) findViewById(R.id.rnview);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);
}

至此,RN 頁面已經和原生布局和平共處在一屏之內。剩下的問題是:RN 頁面如何返回原生頁面、Android 的物理返回鍵又該如何與 RN 的路由協調——這留待下一篇處理。
Android 網路圖片與網頁原始碼查看器實作
本文示範兩個實用的小工具:網路圖片查看器與網頁原始碼查看器。網路圖片查看器首先需在 AndroidManifest.xml 加入 INTERNET 權限。程式以 Http
Android 如何取得初始狀態下 View 的寬高
在自訂 View 或下拉刷新等情境中,常常需要在初始化階段取得 View 的寬高。然而,在 View 尚未完成 measure 與 layout 之前,getHeight
Android 自定義 View 學習(二):圓形進度條
上一篇我們掌握了自定義 View 的基本用法,這次來做一個稍複雜的效果——一個帶刻度與動畫的圓形進度條。先看效果圖:要實現上面的效果,仍然離不開自定義 View 開頭的四
Android View 繪製流程:從 measure、layout 到 draw
Android 的畫面並非瞬間出現,而是經過一連串測量、佈局與繪製。理解這個流程,能幫助開發者解決自定義 View 顯示異常、位置錯誤或效能問題。 測量:measure