Here are the examples of the java api com.facebook.react.ReactRootView taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
73 Examples
19
Source : PreReactRootViewLoader.java
with Apache License 2.0
from sucese
with Apache License 2.0
from sucese
public static void removeView(String componentName) {
ReactRootView reactRootView = CACHE.get(componentName);
ViewGroup parentView = (ViewGroup) reactRootView.getParent();
if (parentView != null) {
parentView.removeView(reactRootView);
}
}
19
Source : PreReactRootViewLoader.java
with Apache License 2.0
from sucese
with Apache License 2.0
from sucese
public static void preLoad(Activity activity, String componentName) {
if (CACHE.get(componentName) == null) {
return;
}
ReactRootView reactRootView = new ReactRootView(activity);
reactRootView.startReactApplication(Vinci.getReactNativeHost().getReactInstanceManager(), componentName, null);
CACHE.put(componentName, reactRootView);
}
19
Source : MainActivity.java
with MIT License
from sonnylazuardi
with MIT License
from sonnylazuardi
public clreplaced MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
public ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
private static final int OVERLAY_PERMISSION_REQ_CODE = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
} else {
this.initializePage();
}
} else {
this.initializePage();
}
}
private void initializePage() {
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder().setApplication(getApplication()).setBundlereplacedetName("index.android.bundle").setJSMainModuleName("index.android").addPackage(new MainReactPackage()).addPackage(new ImageIntentPackage()).setUseDeveloperSupport(BuildConfig.DEBUG).setInitialLifecycleState(LifecycleState.RESUMED).build();
mReactRootView.startReactApplication(mReactInstanceManager, "Clarifai", null);
setContentView(com.sonnylab.imageintent.R.layout.activity_main);
((RelativeLayout) findViewById(com.sonnylab.imageintent.R.id.view_container)).addView(mReactRootView);
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause(this);
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy();
}
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
} else {
this.initializePage();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
}
19
Source : RNWorkWorldFragment.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
public clreplaced RNWorkWorldFragment extends RNBaseFragment implements IMNotificaitonCenter.NotificationCenterDelegate, PermissionCallback {
private static final String MODULE = "WorkWorld";
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
private Activity activity;
private static final int PERMISSION_REQUIRE = PermissionDispatcher.getRequestCode();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public void didReceivedNotification(String key, Object... args) {
}
@Override
public void responsePermission(int requestCode, boolean granted) {
}
}
19
Source : RNMineFragment.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
/**
* Created by hubin on 2018/3/27.
*/
public clreplaced RNMineFragment extends RNBaseFragment implements IMNotificaitonCenter.NotificationCenterDelegate {
private static final String MODULE = "MySetting";
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
private Activity activity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mReactRootView = new ReactRootView(context);
activity = getActivity();
mReactInstanceManager = QtalkServiceRNViewInstanceManager.getInstanceManager(activity);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConnectionUtil.getInstance().addEvent(this, QtalkEvent.SHOW_MY_INFO);
// ConnectionUtil.getInstance().addEvent(this, QtalkEvent.LOGIN_EVENT);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
return mReactRootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mReactRootView.startReactApplication(mReactInstanceManager, MODULE, getDefaultBundle());
}
@Override
protected void onFragmentFirstVisible() {
super.onFragmentFirstVisible();
}
public static Bundle getDefaultBundle() {
Bundle bundle = new Bundle();
return bundle;
}
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
try {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.clreplaced).emit(eventName, params);
} catch (Exception _ex) {
// null bridge
}
}
public void clearBridge() {
WritableNativeMap map = new WritableNativeMap();
sendEvent(mReactInstanceManager.getCurrentReactContext(), "QIM_RN_Will_Show", map);
}
@Override
public void didReceivedNotification(String key, Object... args) {
switch(key) {
case QtalkEvent.SHOW_MY_INFO:
clearBridge();
break;
}
}
// @Override
// public void onDestroy() {
// super.onDestroy();
// if (mReactInstanceManager != null) {
// mReactInstanceManager.onHostDestroy(getActivity());
// }
//
// if (mReactRootView != null) {
// mReactRootView.unmountReactApplication();
// mReactRootView = null;
// }
// ConnectionUtil.getInstance().removeEvent(this, QtalkEvent.SHOW_MY_INFO);
// }
}
19
Source : RNFoundFragment.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
/**
* Created by hubin on 2018/4/4.
*/
public clreplaced RNFoundFragment extends RNBaseFragment implements IMNotificaitonCenter.NotificationCenterDelegate {
private static final String MODULE = "FoundPage";
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
private Activity activity;
private PermissionListener mPermissionListener;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mReactRootView = new ReactRootView(context);
activity = getActivity();
mReactInstanceManager = QtalkServiceRNViewInstanceManager.getInstanceManager(activity);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConnectionUtil.getInstance().addEvent(this, QtalkEvent.LOGIN_EVENT);
}
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
try {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.clreplaced).emit(eventName, params);
} catch (Exception _ex) {
// null bridge
}
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// super.onCreateView(inflater, container, savedInstanceState);
return mReactRootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mReactRootView.startReactApplication(mReactInstanceManager, MODULE, getDefaultBundle());
}
public static Bundle getDefaultBundle() {
Bundle bundle = new Bundle();
bundle.putString("domain", QtalkNavicationService.getInstance().getXmppdomain());
// 暂时修改
return bundle;
}
public void clearBridge() {
if (mReactInstanceManager != null) {
WritableNativeMap map = new WritableNativeMap();
sendEvent(mReactInstanceManager.getCurrentReactContext(), "QIM_RN_Will_Show", map);
}
}
@Override
public void unbundling() {
super.unbundling();
mReactRootView.unmountReactApplication();
}
@Override
public void didReceivedNotification(String key, Object... args) {
switch(key) {
case QtalkEvent.LOGIN_EVENT:
if (args[0].equals(LoginStatus.Login)) {
clearBridge();
}
}
}
}
19
Source : RNContactsFragment.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
/**
* Created by hubin on 2018/3/28.
*/
public clreplaced RNContactsFragment extends RNBaseFragment implements IMNotificaitonCenter.NotificationCenterDelegate {
private static final String MODULE = "Contacts";
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
private Activity activity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mReactRootView = new ReactRootView(context);
activity = getActivity();
mReactInstanceManager = QtalkServiceRNViewInstanceManager.getInstanceManager(activity);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addEvent();
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
// if(getActivity() !=null && getActivity().getFragmentManager().isDestroyed()){//fix IllegalStateException: Can't access ViewModels from
// RNViewModel rnViewModel = ViewModelProviders.of(getActivity()).get("RnVM",RNViewModel.clreplaced);
// rnViewModel.getUnreadCountLD().observe(this, new Observer<Integer>() {
// @Override
// public void onChanged(@Nullable Integer integer) {
// WritableNativeMap map = new WritableNativeMap();
// map.putString("UnreadCount",String.valueOf(integer));
// sendEvent(mReactInstanceManager.getCurrentReactContext(),"QIM_RN_UnreadCount",map);
// }
// });
// }
// }
}
public void addEvent() {
ConnectionUtil.getInstance().addEvent(this, QtalkEvent.Update_Buddy);
ConnectionUtil.getInstance().addEvent(this, QtalkEvent.USER_GET_FRIEND);
ConnectionUtil.getInstance().addEvent(this, QtalkEvent.LOGIN_EVENT);
}
public void removeEvent() {
ConnectionUtil.getInstance().removeEvent(this, QtalkEvent.USER_GET_FRIEND);
ConnectionUtil.getInstance().removeEvent(this, QtalkEvent.Update_Buddy);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return mReactRootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mReactRootView.startReactApplication(mReactInstanceManager, MODULE, getDefaultBundle());
}
@Override
protected void onFragmentFirstVisible() {
super.onFragmentFirstVisible();
}
public static Bundle getDefaultBundle() {
Bundle bundle = new Bundle();
return bundle;
}
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
try {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.clreplaced).emit(eventName, params);
} catch (Exception _ex) {
// null bridge
}
}
public void clearBridge() {
WritableNativeMap map = new WritableNativeMap();
sendEvent(mReactInstanceManager.getCurrentReactContext(), "QIM_RN_Will_Show", map);
}
@Override
public void didReceivedNotification(String key, Object... args) {
switch(key) {
// case QtalkEvent.Update_Buddy:
// //请求最新的好友
// clearBridge();
// break;
case QtalkEvent.USER_GET_FRIEND:
// 从数据库拿好友列表
clearBridge();
break;
case QtalkEvent.LOGIN_EVENT:
if (args[0].equals(LoginStatus.Login)) {
Logger.i("开始获取好友列表");
ConnectionUtil.getInstance().getFriends("");
}
}
}
}
19
Source : RNCalendarFragment.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
public clreplaced RNCalendarFragment extends RNBaseFragment implements IMNotificaitonCenter.NotificationCenterDelegate, PermissionCallback {
private static final String MODULE = "TravelCalendar";
private ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
private Activity activity;
private static final int PERMISSION_REQUIRE = PermissionDispatcher.getRequestCode();
@Override
public void onAttach(Context context) {
super.onAttach(context);
mReactRootView = new ReactRootView(context);
activity = getActivity();
mReactInstanceManager = QtalkServiceRNViewInstanceManager.getInstanceManager(activity);
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addEvent();
}
public void addEvent() {
ConnectionUtil.getInstance().addEvent(this, QtalkEvent.UPDATE_TRIP);
// ConnectionUtil.getInstance().addEvent(this, QtalkEvent.Update_Buddy);
// ConnectionUtil.getInstance().addEvent(this,QtalkEvent.USER_GET_FRIEND);
// ConnectionUtil.getInstance().addEvent(this,QtalkEvent.LOGIN_EVENT);
}
public void removeEvent() {
ConnectionUtil.getInstance().removeEvent(this, QtalkEvent.UPDATE_TRIP);
// ConnectionUtil.getInstance().removeEvent(this,QtalkEvent.USER_GET_FRIEND);
// ConnectionUtil.getInstance().removeEvent(this,QtalkEvent.Update_Buddy);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return mReactRootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mReactRootView.startReactApplication(mReactInstanceManager, MODULE, getDefaultBundle());
}
@Override
protected void onFragmentFirstVisible() {
super.onFragmentFirstVisible();
checkPermission();
}
/**
* 检查权限
*/
private void checkPermission() {
PermissionDispatcher.requestPermissionWithCheck(getActivity(), new int[] { PermissionDispatcher.REQUEST_READ_CALENDAR, PermissionDispatcher.REQUEST_WRITE_CALENDAR /*, PermissionDispatcher.REQUEST_READ_PHONE_STATE*/
}, this, PERMISSION_REQUIRE);
}
public static Bundle getDefaultBundle() {
Bundle bundle = new Bundle();
return bundle;
}
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
try {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.clreplaced).emit(eventName, params);
} catch (Exception _ex) {
// null bridge
}
}
public void clearBridge() {
WritableNativeMap map = new WritableNativeMap();
sendEvent(mReactInstanceManager.getCurrentReactContext(), "QIM_RN_Will_Show", map);
}
@Override
public void didReceivedNotification(String key, Object... args) {
switch(key) {
case QtalkEvent.UPDATE_TRIP:
// 请求最新的好友
clearBridge();
break;
}
}
@Override
public void responsePermission(int requestCode, boolean granted) {
if (requestCode == PERMISSION_REQUIRE) {
if (!granted) {
Toast.makeText(getActivity(), "没有日历权限,Qtalk无法同步日程到系统日历", Toast.LENGTH_LONG).show();
// finish();
return;
}
}
}
}
19
Source : QtalkServiceRNActivity.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
/**
* Created by hubin on 2018/1/18.
*/
public clreplaced QtalkServiceRNActivity extends Activity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity, IMNotificaitonCenter.NotificationCenterDelegate {
public ReactInstanceManager mReactInstanceManager;
public ReactInstanceManagerBuilder builder;
public ReactRootView mReactRootView;
private PermissionListener mPermissionListener;
private String module;
private Bundle bundle;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mReactRootView = new ReactRootView(this);
addEvent();
startRNApplicationWithBundle(getExtendBundle());
setContentView(mReactRootView);
}
private void startRNApplicationWithBundle(Bundle extendBundle) {
if (mReactInstanceManager == null) {
mReactInstanceManager = QtalkServiceRNViewInstanceManager.getInstanceManager(this);
}
String module = extendBundle.getString("name");
// render react
mReactRootView.startReactApplication(mReactInstanceManager, module, extendBundle);
}
private Bundle getExtendBundle() {
Intent intent = getIntent();
Uri data = intent.getData();
Bundle bundle = intent.getExtras();
if (bundle == null) {
bundle = new Bundle();
}
if (data != null) {
// schema 跳转
HashMap<String, String> map = Protocol.splitParams(data);
for (Map.Entry<String, String> entry : map.entrySet()) {
bundle.putString(entry.getKey(), entry.getValue());
}
bundle.putString("name", map.get("module"));
} else {
// intent 跳转
bundle.putString("name", intent.getStringExtra("module"));
}
return bundle;
}
@Override
public void invokeDefaultOnBackPressed() {
onBackPressed();
}
@Override
public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
mPermissionListener = listener;
ActivityCompat.requestPermissions(this, permissions, requestCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy(this);
}
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
}
removeEvent();
}
public void updatePage() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy(this);
mReactInstanceManager = null;
QtalkServiceRNViewInstanceManager.mReactInstanceManager = null;
}
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
}
mReactRootView = new ReactRootView(this);
startRNApplicationWithBundle(getExtendBundle());
setContentView(mReactRootView);
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, new DefaultHardwareBackBtnHandler() {
@Override
public void invokeDefaultOnBackPressed() {
finish();
}
});
}
}
private void addEvent() {
ConnectionUtil.getInstance().addEvent(this, QtalkEvent.RN_UPDATE);
}
private void removeEvent() {
ConnectionUtil.getInstance().removeEvent(this, QtalkEvent.RN_UPDATE);
}
@Override
public void didReceivedNotification(String key, Object... args) {
switch(key) {
case QtalkEvent.RN_UPDATE:
updatePage();
break;
}
}
}
19
Source : QTalkSearchActivity.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
/**
* Created by wangyu.wang on 2016/11/30.
*/
public clreplaced QTalkSearchActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
private static ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mReactInstanceManager == null) {
// if (TextUtils.isEmpty(QtalkNavicationService.getInstance().getNewSerarchUrl())) {
// mReactInstanceManager = QTalkSearchRNViewOldInstanceManager.getInstanceManager(getApplication());
// } else {
// if(QtalkNavicationService.getInstance().getXmppdomain().equals("ejabhost1")){
if (IMDatabaseManager.getInstance().getFocusSearch()) {
mReactInstanceManager = QTalkSearchRNViewOldInstanceManager.getInstanceManager(getApplication());
} else {
mReactInstanceManager = QTalkSearchRNViewInstanceManager.getInstanceManager(getApplication());
}
// }else{
// mReactInstanceManager = QTalkSearchRNViewOldInstanceManager.getInstanceManager(getApplication());
// }
// }
}
mReactRootView = new ReactRootView(this);
// render react
// if (mReactInstanceManager == null) {
// if (TextUtils.isEmpty(QtalkNavicationService.getInstance().getNewSerarchUrl())) {
// // mReactInstanceManager = QTalkSearchRNViewOldInstanceManager.getInstanceManager(getApplication());
// mReactRootView.startReactApplication(mReactInstanceManager, QTalkSearchRNViewOldInstanceManager.MODULE, getExtendBundle());
// } else {
// if(QtalkNavicationService.getInstance().getXmppdomain().equals("ejabhost1")) {
if (IMDatabaseManager.getInstance().getFocusSearch()) {
// mReactInstanceManager = QTalkSearchRNViewOldInstanceManager.getInstanceManager(getApplication());
mReactRootView.startReactApplication(mReactInstanceManager, QTalkSearchRNViewOldInstanceManager.MODULE, getExtendBundle());
} else {
// mReactInstanceManager = QTalkSearchRNViewInstanceManager.getInstanceManager(getApplication());
mReactRootView.startReactApplication(mReactInstanceManager, QTalkSearchRNViewInstanceManager.MODULE, getExtendBundle());
}
// }else{
// mReactRootView.startReactApplication(mReactInstanceManager, QTalkSearchRNViewOldInstanceManager.MODULE, getExtendBundle());
// }
// }
// }
// set to content
setContentView(mReactRootView);
}
private Bundle getExtendBundle() {
Bundle bundle = new Bundle();
bundle.putString("server", QtalkNavicationService.getInstance().getSimpleapiurl());
bundle.putString("searchUrl", QtalkNavicationService.getInstance().getNewSerarchUrl());
bundle.putString("singleDefaultPic", QimRNBModule.defaultUserImage);
bundle.putString("mucDefaultPic", QimRNBModule.defaultMucImage);
bundle.putString("imageHost", QtalkNavicationService.getInstance().getInnerFiltHttpHost());
bundle.putString("MyUserId", CurrentPreference.getInstance().getPreferenceUserId());
List<SearchKeyData> list = IMDatabaseManager.getInstance().getLocalSearchKeyHistory(0, 5);
List<String> array = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
array.add(list.get(i).getSearchKey());
}
bundle.putStringArrayList("searchKeyHistory", (ArrayList<String>) array);
return bundle;
}
public static void clearBridge() {
// TODO auto reload
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactRootView != null)
mReactRootView.unmountReactApplication();
if (mReactInstanceManager != null)
mReactInstanceManager.onHostDestroy(this);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
public void invokeDefaultOnBackPressed() {
onBackPressed();
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, new DefaultHardwareBackBtnHandler() {
@Override
public void invokeDefaultOnBackPressed() {
finish();
}
});
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (mReactInstanceManager != null) {
mReactInstanceManager.onActivityResult(mReactInstanceManager.getCurrentReactContext().getCurrentActivity(), requestCode, resultCode, data);
}
}
}
19
Source : QtalkServiceExternalRNActivity.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
public clreplaced QtalkServiceExternalRNActivity extends SwipeBackActivity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {
public static ReactInstanceManager mReactInstanceManager;
public static ReactInstanceManagerBuilder builder;
// 头部导航
protected QtNewActionBar qtNewActionBar;
public static ReactRootView mReactRootView;
private PermissionListener mPermissionListener;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atom_ui_activity_rn_external);
bindView();
}
private void bindView() {
try {
qtNewActionBar = (QtNewActionBar) this.findViewById(R.id.my_action_bar);
setNewActionBar(qtNewActionBar);
boolean isShow = Boolean.parseBoolean(getIntent().getStringExtra("showNativeNav"));
if (isShow) {
String replacedle = getIntent().getStringExtra("navreplacedle");
setActionBarreplacedle(replacedle);
setActionBarVisibility(true);
} else {
setActionBarVisibility(false);
}
// mReactRootView = new ReactRootView(this);
mReactRootView = (ReactRootView) findViewById(R.id.mReactRootView);
startRNApplicationWithBundle(getExtendBundle());
// setContentView(mReactRootView);
} catch (Exception e) {
Logger.i("打开外部RN应用出现不可预知错误:" + e.getMessage());
}
}
private void startRNApplicationWithBundle(Bundle extendBundle) {
String bundleName = extendBundle.getString("Bundle");
String Entrance = extendBundle.getString("Entrance");
if (TextUtils.isEmpty(bundleName)) {
finish();
return;
}
// if (mReactInstanceManager == null) {
mReactInstanceManager = QtalkServiceExternalRNViewInstanceManager.getInstanceManager(this, bundleName, Entrance);
// }
String module = extendBundle.getString("name");
// render react
if (mReactInstanceManager == null) {
return;
}
mReactRootView.startReactApplication(mReactInstanceManager, module, extendBundle);
}
private Bundle getExtendBundle() {
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
bundle.putString("name", intent.getStringExtra("module"));
return bundle;
}
@Override
public void invokeDefaultOnBackPressed() {
onBackPressed();
}
@Override
public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
mPermissionListener = listener;
ActivityCompat.requestPermissions(this, permissions, requestCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy(this);
}
// if (mReactRootView != null) {
// mReactRootView.unmountReactApplication();
// // mReactRootView = null;
// }
}
public void updatePage() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy(this);
mReactInstanceManager = null;
QtalkServiceRNViewInstanceManager.mReactInstanceManager = null;
}
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
}
mReactRootView = new ReactRootView(this);
startRNApplicationWithBundle(getExtendBundle());
setContentView(mReactRootView);
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, new DefaultHardwareBackBtnHandler() {
@Override
public void invokeDefaultOnBackPressed() {
finish();
}
});
}
}
}
19
Source : QtalkOpenTravelCalendar.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
public clreplaced QtalkOpenTravelCalendar extends SwipeBackActivity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity, IMNotificaitonCenter.NotificationCenterDelegate, PermissionCallback {
public ReactInstanceManager mReactInstanceManager;
private ReactRootView mReactRootView;
// 头部导航
protected QtNewActionBar qtNewActionBar;
private PermissionListener mPermissionListener;
private static final int PERMISSION_REQUIRE = PermissionDispatcher.getRequestCode();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.atom_ui_travel_calendar);
bindView();
addEvent();
startRNApplicationWithBundle(getExtendBundle());
bindData();
}
private void bindData() {
setActionBarRightSpecial(0);
// setActionBarSinglereplacedle(mreplacedles[mViewPager.getCurrenreplacedem()]);
setActionBarRightIcon(R.string.atom_ui_new_select_calendar);
setActionBarRightIconClick(new View.OnClickListener() {
@Override
public void onClick(View v) {
TimePickerView tpv = new TimePickerBuilder(QtalkOpenTravelCalendar.this, new OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date, View v) {
String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
IMNotificaitonCenter.getInstance().postMainThreadNotificationName(QtalkEvent.SELECT_DATE, time);
}
}).build();
tpv.show();
}
});
checkPermission();
}
/**
* 检查权限
*/
private void checkPermission() {
PermissionDispatcher.requestPermissionWithCheck(this, new int[] { PermissionDispatcher.REQUEST_READ_CALENDAR, PermissionDispatcher.REQUEST_WRITE_CALENDAR /*, PermissionDispatcher.REQUEST_READ_PHONE_STATE*/
}, this, PERMISSION_REQUIRE);
}
private void bindView() {
qtNewActionBar = (QtNewActionBar) this.findViewById(R.id.my_action_bar);
setNewActionBar(qtNewActionBar);
setActionBarreplacedle("行程");
mReactRootView = (ReactRootView) findViewById(R.id.mReactRootView);
}
private void startRNApplicationWithBundle(Bundle extendBundle) {
if (mReactInstanceManager == null) {
mReactInstanceManager = QtalkServiceRNViewInstanceManager.getInstanceManager(this);
}
String module = extendBundle.getString("name");
// render react
mReactRootView.startReactApplication(mReactInstanceManager, module, extendBundle);
}
private Bundle getExtendBundle() {
Intent intent = getIntent();
Uri data = intent.getData();
Bundle bundle = intent.getExtras();
if (bundle == null) {
bundle = new Bundle();
}
if (data != null) {
// schema 跳转
HashMap<String, String> map = Protocol.splitParams(data);
for (Map.Entry<String, String> entry : map.entrySet()) {
bundle.putString(entry.getKey(), entry.getValue());
}
bundle.putString("name", map.get("module"));
} else {
// intent 跳转
bundle.putString("name", intent.getStringExtra("module"));
}
return bundle;
}
@Override
public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
mPermissionListener = listener;
ActivityCompat.requestPermissions(this, permissions, requestCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (mPermissionListener != null) {
mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy(this);
}
// if (mReactRootView != null) {
// mReactRootView.unmountReactApplication();
// // mReactRootView = null;
// }
removeEvent();
}
public void updatePage() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy(this);
mReactInstanceManager = null;
QtalkServiceRNViewInstanceManager.mReactInstanceManager = null;
}
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
}
mReactRootView = new ReactRootView(this);
startRNApplicationWithBundle(getExtendBundle());
setContentView(mReactRootView);
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, new DefaultHardwareBackBtnHandler() {
@Override
public void invokeDefaultOnBackPressed() {
finish();
}
});
}
}
private void addEvent() {
ConnectionUtil.getInstance().addEvent(this, QtalkEvent.RN_UPDATE);
ConnectionUtil.getInstance().addEvent(this, QtalkEvent.UPDATE_TRIP);
}
private void removeEvent() {
ConnectionUtil.getInstance().removeEvent(this, QtalkEvent.RN_UPDATE);
ConnectionUtil.getInstance().removeEvent(this, QtalkEvent.UPDATE_TRIP);
}
@Override
public void invokeDefaultOnBackPressed() {
onBackPressed();
}
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
try {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.clreplaced).emit(eventName, params);
} catch (Exception _ex) {
// null bridge
}
}
@Override
public void didReceivedNotification(String key, Object... args) {
switch(key) {
case QtalkEvent.RN_UPDATE:
updatePage();
break;
case QtalkEvent.UPDATE_TRIP:
// 请求最新的好友
WritableNativeMap map = new WritableNativeMap();
sendEvent(mReactInstanceManager.getCurrentReactContext(), "QIM_RN_Will_Show", map);
// clearBridge();
break;
}
}
@Override
public void responsePermission(int requestCode, boolean granted) {
if (requestCode == PERMISSION_REQUIRE) {
if (!granted) {
Toast.makeText(this, "没有日历权限,Qtalk无法同步日程到系统日历", Toast.LENGTH_LONG).show();
// finish();
return;
}
}
}
}
19
Source : ReactNativeDemoLibrary.java
with MIT License
from petterh
with MIT License
from petterh
/**
* Create a react-native "HelloWorld" {@link ReactRootView}.
*
* @param activity The {@link Activity} that will host the {@code View}.
* @param useDeveloperSupport Preplaced {@code true} to load JS from development server. This requires
* overlay permission. Host applications should generally preplaced {@code false}.
* Preplaced the same value every time.
* @return a new react-native "HelloWorld" {@link ReactRootView}.
* @exception IllegalArgumentException if {@code activity == null} or this method has previously
* been called with a different value for {@code useDeveloperSupport}.
*/
public static View createHelloWorldView(@NonNull Activity activity, boolean useDeveloperSupport) {
// noinspection ConstantConditions
if (activity == null) {
throw new IllegalArgumentException("Null activity preplaceded to ReactNativeDemoLibrary.start");
}
if (developerSupport == DeveloperSupport.Uninitialized) {
replacedert reactInstanceManager == null;
developerSupport = DeveloperSupport.fromBoolean(useDeveloperSupport);
} else if (!developerSupport.equals(useDeveloperSupport)) {
replacedert reactInstanceManager != null;
throw new IllegalArgumentException("The value of useDeveloperSupport may not be changed during the app's lifetime.");
}
if (reactInstanceManager == null) {
reactInstanceManager = ReactInstanceManager.builder().setApplication(activity.getApplication()).setBundlereplacedetName("index.android.bundle").setJSMainModulePath("index.android").addPackage(new MainReactPackage()).addPackage(new DemoReactPackage()).setUseDeveloperSupport(useDeveloperSupport).setInitialLifecycleState(LifecycleState.BEFORE_RESUME).build();
}
ActivityLifeCycleHandler lifeCycleHandler = new ActivityLifeCycleHandler(activity, reactInstanceManager);
activity.getApplication().registerActivityLifecycleCallbacks(lifeCycleHandler);
ReactRootView reactRootView = new ReactRootView(activity);
reactRootView.startReactApplication(reactInstanceManager, "HelloWorld");
return reactRootView;
}
19
Source : ReactPreLoader.java
with Apache License 2.0
from markzhai
with Apache License 2.0
from markzhai
/**
* Pre-load {@link ReactRootView} to local {@link Map}, you may want to
* load it in previous activity.
*/
public static void init(Activity activity, ReactInfo reactInfo) {
if (CACHE_VIEW_MAP.get(reactInfo.getMainComponentName()) != null) {
return;
}
ReactRootView rootView = new ReactRootView(new MutableContextWrapper(activity));
rootView.startReactApplication(((ReactApplication) activity.getApplication()).getReactNativeHost().getReactInstanceManager(), reactInfo.getMainComponentName(), reactInfo.getLaunchOptions());
CACHE_VIEW_MAP.put(reactInfo.getMainComponentName(), rootView);
}
19
Source : ReactPreLoader.java
with Apache License 2.0
from markzhai
with Apache License 2.0
from markzhai
/**
* Remove {@link ReactRootView} from parent.
*/
public static void onDestroy(ReactInfo reactInfo) {
try {
ReactRootView rootView = getRootView(reactInfo);
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
} catch (Throwable e) {
Log.e(TAG, e.getMessage());
}
}
19
Source : MrReactActivity.java
with Apache License 2.0
from markzhai
with Apache License 2.0
from markzhai
/**
* Base Activity for React Native applications.
*
* @author markzhai on 16/8/20
* @version 0.31.0
*/
public abstract clreplaced MrReactActivity extends Activity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {
private static final String TAG = "MrReactActivity";
private static final String REDBOX_PERMISSION_MESSAGE = "Overlay permissions needs to be granted in order for react native apps to run in dev mode";
@Nullable
private PermissionListener mPermissionListener;
@Nullable
private ReactInstanceManager mReactInstanceManager;
@Nullable
private ReactRootView mReactRootView;
private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;
private boolean mDoRefresh = false;
/**
* Returns the launchOptions which will be preplaceded to the {@link ReactInstanceManager}
* when the application is started. By default, this will return null and an empty
* object will be preplaceded to your top level component as its initial props.
* If your React Native application requires props set outside of JS, override
* this method to return the Android.os.Bundle of your desired initial props.
*/
@Nullable
protected Bundle getLaunchOptions() {
return null;
}
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
* e.g. "MoviesApp"
*/
protected abstract String getMainComponentName();
/**
* A subclreplaced may override this method if it needs to use a custom {@link ReactRootView}.
*/
protected ReactRootView createRootView() {
return new ReactRootView(this);
}
/**
* Get the {@link ReactNativeHost} used by this app. By default, replacedumes {@link #getApplication()}
* is an instance of {@link ReactApplication} and calls
* {@link ReactApplication#getReactNativeHost()}. Override this method if your application clreplaced
* does not implement {@code ReactApplication} or you simply have a different mechanism for
* storing a {@code ReactNativeHost}, e.g. as a static field somewhere.
*/
protected ReactNativeHost getReactNativeHost() {
return ((ReactApplication) getApplication()).getReactNativeHost();
}
/**
* Get whether developer support should be enabled or not. By default this delegates to
* {@link ReactNativeHost#getUseDeveloperSupport()}. Override this method if your application
* clreplaced does not implement {@code ReactApplication} or you simply have a different logic for
* determining this (default just checks {@code BuildConfig}).
*/
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getUseDeveloperSupport() && Build.VERSION.SDK_INT >= 23) {
// Get permission to show redbox in dev builds.
if (!Settings.canDrawOverlays(this)) {
Intent serviceIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
startActivity(serviceIntent);
FLog.w(ReactConstants.TAG, REDBOX_PERMISSION_MESSAGE);
Toast.makeText(this, REDBOX_PERMISSION_MESSAGE, Toast.LENGTH_LONG).show();
}
}
mReactRootView = ReactPreLoader.getRootView(getReactInfo());
if (mReactRootView != null) {
Log.i(TAG, "use pre-load view");
MutableContextWrapper contextWrapper = (MutableContextWrapper) mReactRootView.getContext();
contextWrapper.setBaseContext(this);
try {
ViewGroup viewGroup = (ViewGroup) mReactRootView.getParent();
if (viewGroup != null) {
viewGroup.removeView(mReactRootView);
}
} catch (Exception exception) {
Log.e(TAG, "getParent error", exception);
}
} else {
Log.i(TAG, "createRootView");
mReactRootView = createRootView();
if (mReactRootView != null) {
mReactRootView.startReactApplication(getReactNativeHost().getReactInstanceManager(), getMainComponentName(), getLaunchOptions());
}
}
setContentView(mReactRootView);
mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
}
@Override
protected void onPause() {
super.onPause();
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onHostResume(this, this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
ReactPreLoader.onDestroy(getReactInfo());
}
// getReactNativeHost().clear();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onActivityResult(requestCode, resultCode, data);
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (getReactNativeHost().hasInstance() && getUseDeveloperSupport()) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
getReactNativeHost().getReactInstanceManager().showDevOptionsDialog();
return true;
}
if (mDoubleTapReloadRecognizer.didDoubleTapR(keyCode, getCurrentFocus())) {
getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS();
}
}
return super.onKeyUp(keyCode, event);
}
@Override
public void onBackPressed() {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
@Override
public void onNewIntent(Intent intent) {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onNewIntent(intent);
} else {
super.onNewIntent(intent);
}
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
mPermissionListener = listener;
requestPermissions(permissions, requestCode);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (mPermissionListener != null && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
mPermissionListener = null;
}
}
public abstract ReactInfo getReactInfo();
}
19
Source : ContainerLayout.java
with MIT License
from marijnz
with MIT License
from marijnz
/**
* Created by marijnzwemmer on 11/11/17.
*/
public clreplaced ContainerLayout extends RelativeLayout {
final static int transparant = Color.parseColor("#00000000");
UnityPlayer unityPlayer;
ReactRootView reactRootView;
Context context;
public ContainerLayout(Context context, final UnityPlayer unityPlayer, final ReactRootView reactRootView) {
super(context);
this.unityPlayer = unityPlayer;
this.reactRootView = reactRootView;
this.context = context;
final RelativeLayout subLayout1 = createLayout();
final RelativeLayout subLayout2 = createLayout();
subLayout1.setBackground(new ColorDrawable(transparant));
subLayout2.setBackground(new ColorDrawable(transparant));
subLayout1.addView(unityPlayer);
subLayout2.addView(reactRootView);
addView(subLayout1);
addView(subLayout2);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// replaceduming that React is on top Unity, first let React handle touches as usual, then manually Unity
onTouchEvent(ev);
unityPlayer.onTouchEvent(ev);
return false;
}
private RelativeLayout createLayout() {
RelativeLayout layout = new RelativeLayout(context);
layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
layout.setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
return layout;
}
}
19
Source : TurbolinksViewFrame.java
with MIT License
from lazaronixon
with MIT License
from lazaronixon
public clreplaced TurbolinksViewFrame extends FrameLayout {
private TurbolinksView turbolinksView;
private ReactRootView customView;
public TurbolinksViewFrame(@NonNull Context context) {
super(context);
resolveAttribute(context, null, 0, 0);
}
public TurbolinksViewFrame(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
resolveAttribute(context, attrs, 0, 0);
}
public TurbolinksViewFrame(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
resolveAttribute(context, attrs, defStyleAttr, 0);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public TurbolinksViewFrame(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
resolveAttribute(context, attrs, defStyleAttr, defStyleRes);
}
private void resolveAttribute(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
turbolinksView = new TurbolinksView(context, attrs, defStyleAttr, defStyleRes);
addView(turbolinksView);
}
public TurbolinksView getTurbolinksView() {
return turbolinksView;
}
public void renderComponent(ReactInstanceManager manager, TurbolinksRoute route) {
removeView(customView);
turbolinksView.setVisibility(View.GONE);
customView = new ReactRootView(getContext());
customView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
customView.startReactApplication(manager, route.getComponent(), route.getPreplacedProps());
addView(customView);
}
public void reload(TurbolinksSession session, String location) {
turbolinksView.setVisibility(View.VISIBLE);
removeView(customView);
session.visit(location);
}
}
19
Source : WebActivity.java
with MIT License
from lazaronixon
with MIT License
from lazaronixon
public clreplaced WebActivity extends ApplicationActivity implements TurbolinksAdapter {
public static final int HTTP_FAILURE = 0;
public static final int NETWORK_FAILURE = 1;
public static final String TURBOLINKS_ERROR = "turbolinksError";
public static final String TURBOLINKS_MESSAGE = "turbolinksMessage";
public static final String TURBOLINKS_VISIT_COMPLETED = "turbolinksVisitCompleted";
public static final String TURBOLINKS_VISIT = "turbolinksVisit";
private TurbolinksViewFrame turbolinksViewFrame;
private String messageHandler;
private String userAgent;
private String loadingView;
private String injectedJavaScript;
private ReactRootView progressIndicator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
setupToolBar();
turbolinksViewFrame = findViewById(R.id.turbolinks_view);
messageHandler = getIntent().getStringExtra(INTENT_MESSAGE_HANDLER);
userAgent = getIntent().getStringExtra(INTENT_USER_AGENT);
loadingView = getIntent().getStringExtra(INTENT_LOADING_VIEW);
injectedJavaScript = getIntent().getStringExtra(INTENT_INJECTED_JAVASCRIPT);
setupAppOptions();
visitTurbolinksView();
}
@Override
protected void onRestart() {
super.onRestart();
TurbolinksSession.getDefault(this).activity(this).adapter(this).restoreWithCachedSnapshot(true).view(turbolinksViewFrame.getTurbolinksView()).visit(route.getUrl());
}
@Override
protected void onDestroy() {
super.onDestroy();
if (progressIndicator != null) {
progressIndicator.unmountReactApplication();
progressIndicator = null;
}
}
@Override
public void onReceivedError(int errorCode) {
if (errorCode < 0) {
WritableMap params = Arguments.createMap();
params.putInt("code", NETWORK_FAILURE);
params.putInt("statusCode", errorCode);
params.putString("description", "Network Failure.");
getEventEmitter().emit(TURBOLINKS_ERROR, params);
}
}
@Override
public void requestFailedWithStatusCode(int statusCode) {
WritableMap params = Arguments.createMap();
params.putInt("code", HTTP_FAILURE);
params.putInt("statusCode", statusCode);
params.putString("description", "HTTP Failure. Code:" + statusCode);
getEventEmitter().emit(TURBOLINKS_ERROR, params);
}
@Override
public void visitProposedToLocationWithAction(String location, String action) {
try {
WritableMap params = Arguments.createMap();
URL urlLocation = new URL(location);
params.putString("component", null);
params.putString("url", urlLocation.toString());
params.putString("path", urlLocation.getPath());
params.putString("action", action);
getEventEmitter().emit(TURBOLINKS_VISIT, params);
} catch (MalformedURLException e) {
Log.e(ReactConstants.TAG, "Error parsing URL. " + e.toString());
}
}
@Override
public void visitCompleted() {
renderreplacedle(route.getreplacedle(), route.getSubreplacedle());
handleVisitCompleted();
handleWebreplacedlePress();
}
@Override
public void onPageFinished() {
if (injectedJavaScript != null) {
sessionWebView().evaluateJavascript(injectedJavaScript, null);
}
}
@Override
public void pageInvalidated() {
}
@Override
public void renderreplacedle(String replacedle, String subreplacedle) {
getSupportActionBar().setreplacedle(replacedle != null ? replacedle : sessionWebView().getreplacedle());
getSupportActionBar().setSubreplacedle(subreplacedle);
}
@Override
public void reloadVisitable() {
turbolinksViewFrame.reload(TurbolinksSession.getDefault(this), route.getUrl());
}
@Override
public void reloadSession() {
flushCookies();
TurbolinksSession.getDefault(this).resetToColdBoot();
TurbolinksSession.getDefault(this).visit(route.getUrl());
}
@Override
public void renderComponent(TurbolinksRoute route) {
turbolinksViewFrame.renderComponent(getReactInstanceManager(), route);
}
@Override
public void injectJavaScript(String script) {
sessionWebView().evaluateJavascript(script, null);
}
@JavascriptInterface
public void postMessage(String message) {
getEventEmitter().emit(TURBOLINKS_MESSAGE, message);
}
@Override
public void handleActionPress(int itemId) {
try {
URL urlLocation = new URL(sessionWebView().getUrl());
WritableMap params = Arguments.createMap();
params.putString("component", null);
params.putString("url", urlLocation.toString());
params.putString("path", urlLocation.getPath());
params.putInt("actionId", itemId);
getEventEmitter().emit(TURBOLINKS_ACTION_PRESS, params);
} catch (MalformedURLException e) {
Log.e(ReactConstants.TAG, "Error parsing URL. " + e.toString());
}
}
private WebView sessionWebView() {
return TurbolinksSession.getDefault(this).getWebView();
}
private void setupAppOptions() {
if (isInitial()) {
TurbolinksSession session = TurbolinksSession.getDefault(this);
WebSettings settings = session.getWebView().getSettings();
if (userAgent != null) {
settings.setUserAgentString(settings.getUserAgentString() + " " + userAgent);
}
if (loadingView != null) {
setupProgressView(session, turbolinksViewFrame.getTurbolinksView(), loadingView);
}
if (messageHandler != null)
session.addJavascriptInterface(this, messageHandler);
}
}
private void setupProgressView(TurbolinksSession turbolinksSession, TurbolinksView turbolinksView, String loadingView) {
View progressView = LayoutInflater.from(this).inflate(R.layout.custom_progress, turbolinksView, false);
progressView.setBackground(new ColorDrawable(Color.WHITE));
progressIndicator = progressView.findViewById(R.id.turbolinks_custom_progress_indicator);
progressIndicator.startReactApplication(getReactInstanceManager(), loadingView, null);
turbolinksSession.progressView(progressView, progressIndicator.getId(), 500);
}
private void handleWebreplacedlePress() {
try {
URL urlLocation = new URL(sessionWebView().getUrl());
handlereplacedlePress(null, urlLocation.toString(), urlLocation.getPath());
} catch (MalformedURLException e) {
Log.e(ReactConstants.TAG, "Error parsing URL. " + e.toString());
}
}
private void handleVisitCompleted() {
try {
URL urlLocation = new URL(sessionWebView().getUrl());
WritableMap params = Arguments.createMap();
params.putString("url", urlLocation.toString());
params.putString("path", urlLocation.getPath());
getEventEmitter().emit(TURBOLINKS_VISIT_COMPLETED, params);
} catch (MalformedURLException e) {
Log.e(ReactConstants.TAG, "Error parsing URL. " + e.toString());
}
}
private void visitTurbolinksView() {
TurbolinksSession.getDefault(this).activity(this).adapter(this).view(turbolinksViewFrame.getTurbolinksView()).visit(route.getUrl());
}
@SuppressWarnings("deprecation")
private void flushCookies() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
}
}
19
Source : NativeActivity.java
with MIT License
from lazaronixon
with MIT License
from lazaronixon
public clreplaced NativeActivity extends ApplicationActivity {
private ReactRootView rootView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_native);
setupToolBar();
renderreplacedle(route.getreplacedle(), route.getSubreplacedle());
handlereplacedlePress(route.getComponent(), null, null);
rootView = findViewById(R.id.react_root_view);
rootView.startReactApplication(getReactInstanceManager(), route.getComponent(), route.getPreplacedProps());
}
@Override
protected void onDestroy() {
super.onDestroy();
rootView.unmountReactApplication();
rootView = null;
}
@Override
public void reloadSession() {
TurbolinksSession.getDefault(this).resetToColdBoot();
}
@Override
public void renderComponent(TurbolinksRoute route) {
}
@Override
public void reloadVisitable() {
}
@Override
public void injectJavaScript(String script) {
}
@Override
public void handleActionPress(int itemId) {
WritableMap params = Arguments.createMap();
params.putString("component", route.getComponent());
params.putString("url", null);
params.putString("path", null);
params.putInt("actionId", itemId);
getEventEmitter().emit(TURBOLINKS_ACTION_PRESS, params);
}
}
19
Source : ReactFragment.java
with Apache License 2.0
from hudl
with Apache License 2.0
from hudl
/**
* A {@link Fragment} which loads a React Native Component from your React Native JS Bundle.
* <p>
* NOTE: You can achieve the same behaviour with an Activity by extending
* {@link com.facebook.react.ReactActivity}
*/
public clreplaced ReactFragment extends Fragment implements PermissionAwareActivity {
public static final String ARG_COMPONENT_NAME = "arg_component_name";
public static final String ARG_LAUNCH_OPTIONS = "arg_launch_options";
/**
* @param componentName The name of the react native component
* @param launchOptions Optional launch options
* @return A new instance of fragment ReactFragment.
*/
private static ReactFragment newInstance(@NonNull String componentName, Bundle launchOptions) {
ReactFragment fragment = new ReactFragment();
Bundle args = new Bundle();
args.putString(ARG_COMPONENT_NAME, componentName);
args.putBundle(ARG_LAUNCH_OPTIONS, launchOptions);
fragment.setArguments(args);
return fragment;
}
private String mComponentName;
private Bundle mLaunchOptions;
private ReactRootView mReactRootView;
@Nullable
private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;
@Nullable
private PermissionListener mPermissionListener;
// region Lifecycle
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mComponentName = getArguments().getString(ARG_COMPONENT_NAME);
mLaunchOptions = getArguments().getBundle(ARG_LAUNCH_OPTIONS);
}
if (mComponentName == null) {
throw new IllegalStateException("Cannot loadApp if component name is null");
}
mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mReactRootView = new ReactRootView(getContext());
mReactRootView.startReactApplication(getReactNativeHost().getReactInstanceManager(), mComponentName, mLaunchOptions);
return mReactRootView;
}
@Override
public void onResume() {
super.onResume();
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onHostResume(getActivity(), (DefaultHardwareBackBtnHandler) getActivity());
}
}
@Override
public void onPause() {
super.onPause();
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onHostPause(getActivity());
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
}
if (getReactNativeHost().hasInstance()) {
ReactInstanceManager reactInstanceMgr = getReactNativeHost().getReactInstanceManager();
// onDestroy may be called on a ReactFragment after another ReactFragment has been
// created and resumed with the same React Instance Manager. Make sure we only clean up
// host's React Instance Manager if no other React Fragment is actively using it.
if (reactInstanceMgr.getLifecycleState() != LifecycleState.RESUMED) {
reactInstanceMgr.onHostDestroy(getActivity());
getReactNativeHost().clear();
}
}
}
// endregion
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (mPermissionListener != null && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
mPermissionListener = null;
}
}
// region PermissionAwareActivity
@Override
public int checkPermission(String permission, int pid, int uid) {
return getActivity().checkPermission(permission, pid, uid);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public int checkSelfPermission(String permission) {
return getActivity().checkSelfPermission(permission);
}
@TargetApi(Build.VERSION_CODES.M)
@Override
public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
mPermissionListener = listener;
requestPermissions(permissions, requestCode);
}
// endregion
// region Helpers
/**
* Helper to forward hardware back presses to our React Native Host
*/
public void onBackPressed() {
if (getReactNativeHost().hasInstance()) {
getReactNativeHost().getReactInstanceManager().onBackPressed();
}
}
/**
* Helper to forward onKeyUp commands from our host Activity.
* This allows ReactFragment to handle double tap reloads and dev menus
*
* @param keyCode keyCode
* @param event event
* @return true if we handled onKeyUp
*/
@SuppressWarnings("unused")
public boolean onKeyUp(int keyCode, KeyEvent event) {
boolean handled = false;
if (getReactNativeHost().getUseDeveloperSupport() && getReactNativeHost().hasInstance()) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
getReactNativeHost().getReactInstanceManager().showDevOptionsDialog();
handled = true;
}
boolean didDoubleTapR = replacedertions.replacedertNotNull(mDoubleTapReloadRecognizer).didDoubleTapR(keyCode, getActivity().getCurrentFocus());
if (didDoubleTapR) {
getReactNativeHost().getReactInstanceManager().getDevSupportManager().handleReloadJS();
handled = true;
}
}
return handled;
}
// endregion
/**
* Get the {@link ReactNativeHost} used by this app. By default, replacedumes
* {@link Activity#getApplication()} is an instance of {@link ReactApplication} and calls
* {@link ReactApplication#getReactNativeHost()}. Override this method if your application clreplaced
* does not implement {@code ReactApplication} or you simply have a different mechanism for
* storing a {@code ReactNativeHost}, e.g. as a static field somewhere.
*/
protected ReactNativeHost getReactNativeHost() {
return ((ReactApplication) getActivity().getApplication()).getReactNativeHost();
}
/**
* Builder clreplaced to help instantiate a {@link ReactFragment}
*/
public static clreplaced Builder {
private final String mComponentName;
private Bundle mLaunchOptions;
/**
* Returns new Builder for creating a {@link ReactFragment}
*
* @param componentName The name of your React Native component
*/
public Builder(String componentName) {
mComponentName = componentName;
}
/**
* Set the Launch Options for our React Native instance.
*
* @param launchOptions launchOptions
* @return Builder
*/
public Builder setLaunchOptions(Bundle launchOptions) {
mLaunchOptions = launchOptions;
return this;
}
public ReactFragment build() {
return ReactFragment.newInstance(mComponentName, mLaunchOptions);
}
}
}
19
Source : UIManagerModuleTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
/**
* Verifies removeSubviewsFromContainerWithID works by adding subviews, removing them, and
* checking that the final number of children is correct.
*/
@Test
public void testRemoveSubviewsFromContainerWithID() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = uiManager.addRootView(rootView);
final int containerTag = rootTag + 1;
final int containerSiblingTag = containerTag + 1;
uiManager.createView(containerTag, ReactViewManager.REACT_CLreplaced, rootTag, JavaOnlyMap.of("collapsable", false));
uiManager.createView(containerSiblingTag, ReactViewManager.REACT_CLreplaced, rootTag, JavaOnlyMap.of("collapsable", false));
addChild(uiManager, rootTag, containerTag, 0);
addChild(uiManager, rootTag, containerSiblingTag, 1);
uiManager.createView(containerTag + 2, ReactTextViewManager.REACT_CLreplaced, rootTag, JavaOnlyMap.of("collapsable", false));
uiManager.createView(containerTag + 3, ReactTextViewManager.REACT_CLreplaced, rootTag, JavaOnlyMap.of("collapsable", false));
addChild(uiManager, containerTag, containerTag + 2, 0);
addChild(uiManager, containerTag, containerTag + 3, 1);
uiManager.onBatchComplete();
executePendingFrameCallbacks();
replacedertThat(rootView.getChildCount()).isEqualTo(2);
replacedertThat(((ViewGroup) rootView.getChildAt(0)).getChildCount()).isEqualTo(2);
uiManager.removeSubviewsFromContainerWithID(containerTag);
uiManager.onBatchComplete();
executePendingFrameCallbacks();
replacedertThat(rootView.getChildCount()).isEqualTo(2);
replacedertThat(((ViewGroup) rootView.getChildAt(0)).getChildCount()).isEqualTo(0);
}
19
Source : FabricUIManagerTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
@Test
public void testSealReactShadowNode() {
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = mFabricUIManager.addRootView(rootView);
String viewClreplaced = ReactViewManager.REACT_CLreplaced;
ReactShadowNode container = mFabricUIManager.createNode(6, viewClreplaced, rootTag, null, randomInstanceHandle());
List<ReactShadowNode> childSet = mFabricUIManager.createChildSet(rootTag);
mFabricUIManager.appendChildToSet(childSet, container);
replacedertThat(container.isSealed()).isFalse();
mFabricUIManager.completeRoot(rootTag, childSet);
replacedertThat(container.isSealed()).isTrue();
}
19
Source : FabricUIManagerTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
/**
* Verifies that the reconciliation phase will always set the originalNode field of every node in
* the tree to null once completeRoot has finished to prevent memory leaks.
*/
@Test
public void testRemoveOriginalNodeReferences() {
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = mFabricUIManager.addRootView(rootView);
String viewClreplaced = ReactViewManager.REACT_CLreplaced;
ReactShadowNode aa = mFabricUIManager.createNode(2, viewClreplaced, rootTag, null, randomInstanceHandle());
ReactShadowNode a = mFabricUIManager.createNode(3, viewClreplaced, rootTag, null, randomInstanceHandle());
mFabricUIManager.appendChild(a, aa);
ReactShadowNode bb = mFabricUIManager.createNode(4, viewClreplaced, rootTag, null, randomInstanceHandle());
ReactShadowNode b = mFabricUIManager.createNode(5, viewClreplaced, rootTag, null, randomInstanceHandle());
mFabricUIManager.appendChild(b, bb);
ReactShadowNode container = mFabricUIManager.createNode(6, viewClreplaced, rootTag, null, randomInstanceHandle());
mFabricUIManager.appendChild(container, a);
mFabricUIManager.appendChild(container, b);
List<ReactShadowNode> childSet = mFabricUIManager.createChildSet(rootTag);
mFabricUIManager.appendChildToSet(childSet, container);
mFabricUIManager.completeRoot(rootTag, childSet);
ReactShadowNode aaClone = mFabricUIManager.cloneNodeWithNewProps(aa, null);
ReactShadowNode aClone = mFabricUIManager.cloneNodeWithNewChildren(a);
mFabricUIManager.appendChild(aClone, aaClone);
ReactShadowNode containerClone = mFabricUIManager.cloneNodeWithNewChildren(container);
mFabricUIManager.appendChild(containerClone, b);
mFabricUIManager.appendChild(containerClone, aClone);
List<ReactShadowNode> childSet2 = mFabricUIManager.createChildSet(rootTag);
mFabricUIManager.appendChildToSet(childSet2, containerClone);
mFabricUIManager.completeRoot(rootTag, childSet2);
ReactShadowNode[] nodes = new ReactShadowNode[] { aa, a, bb, b, container, aaClone, aClone, containerClone };
for (ReactShadowNode node : nodes) {
replacedertThat(node.getOriginalReactShadowNode()).isNull();
}
}
19
Source : FabricUIManagerTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
private int createAndRenderRootView() {
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = mFabricUIManager.addRootView(rootView);
int reactTag = mNextReactTag++;
String viewClreplaced = ReactViewManager.REACT_CLreplaced;
ReactShadowNode node = mFabricUIManager.createNode(reactTag, viewClreplaced, rootTag, null, randomInstanceHandle());
List<ReactShadowNode> childSet = mFabricUIManager.createChildSet(rootTag);
mFabricUIManager.appendChildToSet(childSet, node);
mFabricUIManager.completeRoot(rootTag, childSet);
return rootTag;
}
19
Source : FabricUIManagerTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
@Test
public void testCreateNode() {
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = mFabricUIManager.addRootView(rootView);
int reactTag = mNextReactTag++;
String viewClreplaced = ReactViewManager.REACT_CLreplaced;
ReactShadowNode node = mFabricUIManager.createNode(reactTag, viewClreplaced, rootTag, null, randomInstanceHandle());
replacedertThat(reactTag).isEqualTo(node.getReactTag());
replacedertThat(viewClreplaced).isEqualTo(node.getViewClreplaced());
replacedertThat(rootTag).isEqualTo(rootTag);
}
19
Source : FabricUIManagerTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
@Test
public void testCompleteRoot() {
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = mFabricUIManager.addRootView(rootView);
List<ReactShadowNode> children = mFabricUIManager.createChildSet(rootTag);
mFabricUIManager.completeRoot(rootTag, children);
}
19
Source : ViewRenderingTestCase.java
with MIT License
from hellochirag
with MIT License
from hellochirag
public clreplaced ViewRenderingTestCase extends ReactIntegrationTestCase {
private interface ViewRenderingTestModule extends JavaScriptModule {
void renderViewApplication(int rootTag);
void renderMarginApplication(int rootTag);
void renderBorderApplication(int rootTag);
void updateMargins();
void renderTransformApplication(int rootTag);
}
private CatalystInstance mCatalystInstance;
private ReactRootView mRootView;
private int mRootTag;
@Override
protected void setUp() throws Exception {
super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager());
final UIManagerModule uiManager = new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
uiManager.onHostResume();
}
});
waitForIdleSync();
mCatalystInstance = ReactTestHelper.catalystInstanceBuilder(this).addNativeModule(uiManager).addNativeModule(new AndroidInfoModule(getContext())).addNativeModule(new DeviceInfoModule(getContext())).addNativeModule(new AppStateModule(getContext())).addNativeModule(new FakeWebSocketModule()).build();
mRootView = new ReactRootView(getContext());
mRootTag = uiManager.addRootView(mRootView);
}
public void testViewRenderedWithCorrectProperties() {
float expectedOpacity = 0.75f;
int expectedBackgroundColor = Color.rgb(255, 0, 0);
mCatalystInstance.getJSModule(ViewRenderingTestModule.clreplaced).renderViewApplication(mRootTag);
waitForBridgeAndUIIdle();
ReactViewGroup view = getViewAtPath(mRootView);
replacedertEquals("Incorrect (or not applied) opacity", expectedOpacity, view.getAlpha());
replacedertEquals("Incorrect (or not applied) backgroundColor", expectedBackgroundColor, view.getBackgroundColor());
}
public void testMarginsApplied() {
mCatalystInstance.getJSModule(ViewRenderingTestModule.clreplaced).renderMarginApplication(mRootTag);
waitForBridgeAndUIIdle();
View view = getViewAtPath(mRootView);
int expectedMargin = Math.round(PixelUtil.toPixelFromDIP(10));
int expectedMarginLeft = Math.round(PixelUtil.toPixelFromDIP(20));
replacedertEquals(expectedMarginLeft, (int) view.getX());
replacedertEquals(expectedMargin, (int) view.getY());
}
public void testMarginUpdateDoesntForgetPreviousValue() {
mCatalystInstance.getJSModule(ViewRenderingTestModule.clreplaced).renderMarginApplication(mRootTag);
waitForBridgeAndUIIdle();
View view = getViewAtPath(mRootView);
// before: margin: 10, marginLeft: 20
mCatalystInstance.getJSModule(ViewRenderingTestModule.clreplaced).updateMargins();
waitForBridgeAndUIIdle();
// after: margin: 15; it should not forget marginLeft was set to 20
int expectedMargin = Math.round(PixelUtil.toPixelFromDIP(15));
int expectedMarginLeft = Math.round(PixelUtil.toPixelFromDIP(20));
replacedertEquals(expectedMarginLeft, (int) view.getX());
replacedertEquals(expectedMargin, (int) view.getY());
}
public void testBordersApplied() {
mCatalystInstance.getJSModule(ViewRenderingTestModule.clreplaced).renderBorderApplication(mRootTag);
waitForBridgeAndUIIdle();
View view = getViewAtPath(mRootView);
View child = ((ViewGroup) view).getChildAt(0);
int expectedBorderX = Math.round(PixelUtil.toPixelFromDIP(20));
int expectedBorderY = Math.round(PixelUtil.toPixelFromDIP(5));
replacedertEquals(expectedBorderX, (int) child.getX());
replacedertEquals(expectedBorderY, (int) child.getY());
}
public void testTransformations() {
mCatalystInstance.getJSModule(ViewRenderingTestModule.clreplaced).renderTransformApplication(mRootTag);
waitForBridgeAndUIIdle();
View view = getViewAtPath(mRootView);
float expectedTranslateX = PixelUtil.toPixelFromDIP(20);
float expectedTranslateY = PixelUtil.toPixelFromDIP(25);
replacedertEquals(5f, view.getScaleX());
replacedertEquals(10f, view.getScaleY());
replacedertEquals(15f, view.getRotation());
replacedertEquals(expectedTranslateX, view.getTranslationX());
replacedertEquals(expectedTranslateY, view.getTranslationY());
}
}
19
Source : ReactRootViewTestCase.java
with MIT License
from hellochirag
with MIT License
from hellochirag
@Ignore("t6596940: fix intermittently failing test")
public void testResizeRootView() throws Throwable {
final ReactRootView rootView = (ReactRootView) getRootView();
final View childView = rootView.getChildAt(0);
replacedertEquals(rootView.getWidth(), childView.getWidth());
final int newWidth = rootView.getWidth() / 2;
runTestOnUiThread(new Runnable() {
@Override
public void run() {
rootView.setLayoutParams(new FrameLayout.LayoutParams(newWidth, ViewGroup.LayoutParams.MATCH_PARENT));
}
});
getInstrumentation().waitForIdleSync();
waitForBridgeAndUIIdle();
replacedertEquals(newWidth, childView.getWidth());
}
19
Source : ReactRootViewTestCase.java
with MIT License
from hellochirag
with MIT License
from hellochirag
/**
* Verify that removing the root view from hierarchy will trigger subviews removal both on JS and
* native side
*/
public void testRemoveRootView() throws Throwable {
final ReactRootView rootView = (ReactRootView) getRootView();
replacedertEquals(1, rootView.getChildCount());
runTestOnUiThread(new Runnable() {
@Override
public void run() {
ViewGroup parent = (ViewGroup) rootView.getParent();
parent.removeView(rootView);
// removing from parent should not remove child views, child views should be removed as
// an effect of native call to UIManager.removeRootView
replacedertEquals(1, rootView.getChildCount());
}
});
getInstrumentation().waitForIdleSync();
waitForBridgeAndUIIdle();
replacedertEquals("root component should not be automatically unmounted", 0, mRecordingModule.getCalls().size());
replacedertEquals(1, rootView.getChildCount());
runTestOnUiThread(new Runnable() {
@Override
public void run() {
rootView.unmountReactApplication();
}
});
waitForBridgeAndUIIdle();
replacedertEquals(1, mRecordingModule.getCalls().size());
replacedertEquals("RootComponentWillUnmount", mRecordingModule.getCalls().get(0));
replacedertEquals(0, rootView.getChildCount());
}
19
Source : ProgressBarTestCase.java
with MIT License
from hellochirag
with MIT License
from hellochirag
/**
* Test to verify that Progress bar renders as a view of the right size
*/
public clreplaced ProgressBarTestCase extends ReactIntegrationTestCase {
// Has same order of progressBars in ProgressBarTestModule
private static final String[] styleList = new String[] { "Horizontal", "Small", "Large", "Inverse", "SmallInverse", "LargeInverse" };
private static final HashMap<String, Integer> styles = new HashMap<String, Integer>();
static {
styles.put("Horizontal", android.R.attr.progressBarStyleHorizontal);
styles.put("Small", android.R.attr.progressBarStyleSmall);
styles.put("Large", android.R.attr.progressBarStyleLarge);
styles.put("Inverse", android.R.attr.progressBarStyleInverse);
styles.put("SmallInverse", android.R.attr.progressBarStyleSmallInverse);
styles.put("LargeInverse", android.R.attr.progressBarStyleLargeInverse);
}
private static interface ProgressBarTestModule extends JavaScriptModule {
public void renderProgressBarApplication(int rootTag);
}
private UIManagerModule mUIManager;
private CatalystInstance mInstance;
private ReactRootView mRootView;
@Override
protected void setUp() throws Exception {
super.setUp();
List<ViewManager> viewManagers = Arrays.<ViewManager>asList(new ReactViewManager(), new ReactProgressBarViewManager());
mUIManager = new UIManagerModule(getContext(), viewManagers, 0);
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
mUIManager.onHostResume();
}
});
waitForIdleSync();
mInstance = ReactTestHelper.catalystInstanceBuilder(this).addNativeModule(mUIManager).addNativeModule(new AndroidInfoModule(getContext())).addNativeModule(new DeviceInfoModule(getContext())).addNativeModule(new AppStateModule(getContext())).addNativeModule(new FakeWebSocketModule()).build();
mRootView = new ReactRootView(getContext());
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
mRootView.setLayoutParams(new FrameLayout.LayoutParams(metrics.widthPixels, metrics.heightPixels));
int rootTag = mUIManager.addRootView(mRootView);
mInstance.getJSModule(ProgressBarTestModule.clreplaced).renderProgressBarApplication(rootTag);
waitForBridgeAndUIIdle();
}
/**
* Test that the sizes of the progressBars are setup correctly
*/
public void testProgressBarSizes() {
for (String style : styleList) {
ProgressBar newProgressBar = new ProgressBar(getContext(), null, styles.get(style));
final int spec = View.MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, View.MeasureSpec.UNSPECIFIED);
newProgressBar.measure(spec, spec);
final int expectedHeight = newProgressBar.getMeasuredHeight();
// verify correct size of view containing ProgressBar
View viewContainingProgressBar = getViewByTestId(mRootView, style);
replacedertEquals(expectedHeight, viewContainingProgressBar.getHeight());
replacedertTrue(((ViewGroup) viewContainingProgressBar).getChildAt(0) instanceof ProgressBar);
}
}
public void testProgressBarWidth() {
View viewContainingProgressBar = getViewByTestId(mRootView, "Horizontal200");
replacedertEquals(viewContainingProgressBar.getWidth(), dpToPixels(200));
ProgressBar progressBar = (ProgressBar) ((ViewGroup) viewContainingProgressBar).getChildAt(0);
replacedertEquals(progressBar.getWidth(), dpToPixels(200));
}
private int dpToPixels(int dp) {
Resources r = getContext().getResources();
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());
}
}
19
Source : ReactNativePreLoader.java
with MIT License
from HAPENLY
with MIT License
from HAPENLY
/**
* 从当前界面移除 ReactRootView
* @param component
*/
public static void deatchView(String component) {
try {
ReactRootView rootView = getReactRootView(component);
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null) {
parent.removeView(rootView);
}
} catch (Throwable e) {
Log.e("ReactNativePreLoader", e.getMessage());
}
}
19
Source : ReactNativePreLoader.java
with MIT License
from HAPENLY
with MIT License
from HAPENLY
/**
* 初始化ReactRootView,并添加到缓存
* @param activity
* @param componentName
*/
public static void preLoad(Activity activity, String componentName) {
if (CACHE.get(componentName) != null) {
return;
}
// 1.创建ReactRootView
ReactRootView rootView = new ReactRootView(activity);
rootView.startReactApplication(((ReactApplication) activity.getApplication()).getReactNativeHost().getReactInstanceManager(), componentName, null);
// 2.添加到缓存
CACHE.put(componentName, rootView);
}
19
Source : PreLoadReactDelegate.java
with MIT License
from HAPENLY
with MIT License
from HAPENLY
/**
* 处理预加载代理类
* Created by Song on 2017/5/10.
*/
public clreplaced PreLoadReactDelegate {
private final Activity mActivity;
private ReactRootView mReactRootView;
private Callback mPermissionsCallback;
private final String mMainComponentName;
private PermissionListener mPermissionListener;
private final int REQUEST_OVERLAY_PERMISSION_CODE = 1111;
private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;
public PreLoadReactDelegate(Activity activity, @Nullable String mainComponentName) {
this.mActivity = activity;
this.mMainComponentName = mainComponentName;
}
public void onCreate() {
boolean needsOverlayPermission = false;
if (getReactNativeHost().getUseDeveloperSupport() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Get permission to show redbox in dev builds.
if (!Settings.canDrawOverlays(mActivity)) {
needsOverlayPermission = true;
Intent serviceIntent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + mActivity.getPackageName()));
mActivity.startActivityForResult(serviceIntent, REQUEST_OVERLAY_PERMISSION_CODE);
}
}
if (mMainComponentName != null && !needsOverlayPermission) {
// 1.从缓存中获取RootView
mReactRootView = ReactNativePreLoader.getReactRootView(mMainComponentName);
if (mReactRootView == null) {
// 2.缓存中不存在RootView,直接创建
mReactRootView = new ReactRootView(mActivity);
mReactRootView.startReactApplication(getReactInstanceManager(), mMainComponentName, null);
}
// 3.将RootView设置到Activity布局
mActivity.setContentView(mReactRootView);
}
mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
}
public void onResume() {
if (getReactNativeHost().hasInstance()) {
getReactInstanceManager().onHostResume(mActivity, (DefaultHardwareBackBtnHandler) mActivity);
}
if (mPermissionsCallback != null) {
mPermissionsCallback.invoke();
mPermissionsCallback = null;
}
}
public void onPause() {
if (getReactNativeHost().hasInstance()) {
getReactInstanceManager().onHostPause(mActivity);
}
}
public void onDestroy() {
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
}
if (getReactNativeHost().hasInstance()) {
getReactInstanceManager().onHostDestroy(mActivity);
}
// 清除View
ReactNativePreLoader.deatchView(mMainComponentName);
}
public boolean onNewIntent(Intent intent) {
if (getReactNativeHost().hasInstance()) {
getReactInstanceManager().onNewIntent(intent);
return true;
}
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (getReactNativeHost().hasInstance()) {
getReactInstanceManager().onActivityResult(mActivity, requestCode, resultCode, data);
} else {
// Did we request overlay permissions?
if (requestCode == REQUEST_OVERLAY_PERMISSION_CODE && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.canDrawOverlays(mActivity)) {
if (mMainComponentName != null) {
if (mReactRootView != null) {
throw new IllegalStateException("Cannot loadApp while app is already running.");
}
mReactRootView = new ReactRootView(mActivity);
mReactRootView.startReactApplication(getReactInstanceManager(), mMainComponentName, null);
mActivity.setContentView(mReactRootView);
}
}
}
}
}
public boolean onBackPressed() {
if (getReactNativeHost().hasInstance()) {
getReactInstanceManager().onBackPressed();
return true;
}
return false;
}
public boolean onRNKeyUp(int keyCode) {
if (getReactNativeHost().hasInstance() && getReactNativeHost().getUseDeveloperSupport()) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
getReactInstanceManager().showDevOptionsDialog();
return true;
}
boolean didDoubleTapR = replacedertions.replacedertNotNull(mDoubleTapReloadRecognizer).didDoubleTapR(keyCode, mActivity.getCurrentFocus());
if (didDoubleTapR) {
getReactInstanceManager().getDevSupportManager().handleReloadJS();
return true;
}
}
return false;
}
public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
mPermissionListener = listener;
mActivity.requestPermissions(permissions, requestCode);
}
public void onRequestPermissionsResult(final int requestCode, final String[] permissions, final int[] grantResults) {
mPermissionsCallback = new Callback() {
@Override
public void invoke(Object... args) {
if (mPermissionListener != null && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
mPermissionListener = null;
}
}
};
}
/**
* 获取 Application中 ReactNativeHost
* @return
*/
private ReactNativeHost getReactNativeHost() {
return MainApplication.getInstance().getReactNativeHost();
}
/**
* 获取 ReactInstanceManager
* @return
*/
private ReactInstanceManager getReactInstanceManager() {
return getReactNativeHost().getReactInstanceManager();
}
}
19
Source : RNCustomKeyboardKitModule.java
with MIT License
from Bunlong
with MIT License
from Bunlong
public clreplaced RNCustomKeyboardKitModule extends ReactContextBaseJavaModule {
private final ReactApplicationContext reactContext;
private final int TAG_ID = 0xdeadbeaf;
public RNCustomKeyboardKitModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
Handler handle = new Handler(Looper.getMainLooper());
@Override
public String getName() {
return "CustomKeyboardKit";
}
private ReactEditText getEditById(int id) {
// UIViewOperationQueue uii = this.getReactApplicationContext().getNativeModule(UIManagerModule.clreplaced).getUIImplementation().getUIViewOperationQueue();
// return (ReactEditText) uii.getNativeViewHierarchyManager().resolveView(id);
UIViewOperationQueue uii = null;
ReactEditText edit = null;
while (edit == null) {
uii = this.getReactApplicationContext().getNativeModule(UIManagerModule.clreplaced).getUIImplementation().getUIViewOperationQueue();
try {
edit = (ReactEditText) uii.getNativeViewHierarchyManager().resolveView(id);
} catch (IllegalViewOperationException e) {
}
}
return edit;
}
@ReactMethod
public void install(final int tag, final String type) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
final Activity activity = getCurrentActivity();
final ReactEditText edit = getEditById(tag);
if (edit == null) {
return;
}
edit.setTag(TAG_ID, createCustomKeyboardKit(activity, tag, type));
edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(final View v, boolean hasFocus) {
if (hasFocus) {
View keyboard = (View) edit.getTag(TAG_ID);
if (keyboard.getParent() == null) {
activity.addContentView(keyboard, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
((InputMethodManager) getReactApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);
}
});
} else {
View keyboard = (View) edit.getTag(TAG_ID);
if (keyboard.getParent() != null) {
((ViewGroup) keyboard.getParent()).removeView(keyboard);
}
}
}
});
edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
View keyboard = (View) edit.getTag(TAG_ID);
if (keyboard.getParent() == null) {
activity.addContentView(keyboard, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
((InputMethodManager) getReactApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);
}
});
}
});
}
});
}
ReactRootView rootView = null;
private View createCustomKeyboardKit(Activity activity, int tag, String type) {
RelativeLayout layout = new RelativeLayout(activity);
rootView = new ReactRootView(this.getReactApplicationContext());
rootView.setBackgroundColor(Color.WHITE);
Bundle bundle = new Bundle();
bundle.putInt("tag", tag);
bundle.putString("type", type);
rootView.startReactApplication(((ReactApplication) activity.getApplication()).getReactNativeHost().getReactInstanceManager(), "CustomKeyboardKit", bundle);
final float scale = activity.getResources().getDisplayMetrics().density;
RelativeLayout.LayoutParams lParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, Math.round(216 * scale));
lParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layout.addView(rootView, lParams);
// activity.addContentView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
return layout;
}
@ReactMethod
public void uninstall(final int tag) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
final Activity activity = getCurrentActivity();
final ReactEditText edit = getEditById(tag);
if (edit == null) {
return;
}
edit.setTag(TAG_ID, null);
}
});
}
@ReactMethod
public void insertText(final int tag, final String text) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
final Activity activity = getCurrentActivity();
final ReactEditText edit = getEditById(tag);
if (edit == null) {
return;
}
int start = Math.max(edit.getSelectionStart(), 0);
int end = Math.max(edit.getSelectionEnd(), 0);
edit.getText().replace(Math.min(start, end), Math.max(start, end), text, 0, text.length());
}
});
}
@ReactMethod
public void backSpace(final int tag) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
final Activity activity = getCurrentActivity();
final ReactEditText edit = getEditById(tag);
if (edit == null) {
return;
}
int start = Math.max(edit.getSelectionStart(), 0);
int end = Math.max(edit.getSelectionEnd(), 0);
if (start != end) {
edit.getText().delete(start, end);
} else if (start > 0) {
edit.getText().delete(start - 1, end);
}
}
});
}
@ReactMethod
public void doDelete(final int tag) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
final Activity activity = getCurrentActivity();
final ReactEditText edit = getEditById(tag);
if (edit == null) {
return;
}
int start = Math.max(edit.getSelectionStart(), 0);
int end = Math.max(edit.getSelectionEnd(), 0);
if (start != end) {
edit.getText().delete(start, end);
} else if (start > 0) {
edit.getText().delete(start, end + 1);
}
}
});
}
@ReactMethod
public void moveLeft(final int tag) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
final Activity activity = getCurrentActivity();
final ReactEditText edit = getEditById(tag);
if (edit == null) {
return;
}
int start = Math.max(edit.getSelectionStart(), 0);
int end = Math.max(edit.getSelectionEnd(), 0);
if (start != end) {
edit.setSelection(start, start);
} else {
edit.setSelection(start - 1, start - 1);
}
}
});
}
@ReactMethod
public void moveRight(final int tag) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
final Activity activity = getCurrentActivity();
final ReactEditText edit = getEditById(tag);
if (edit == null) {
return;
}
int start = Math.max(edit.getSelectionStart(), 0);
int end = Math.max(edit.getSelectionEnd(), 0);
if (start != end) {
edit.setSelection(end, end);
} else if (start > 0) {
edit.setSelection(end + 1, end + 1);
}
}
});
}
@ReactMethod
public void switchSystemKeyboard(final int tag) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
final Activity activity = getCurrentActivity();
final ReactEditText edit = getEditById(tag);
if (edit == null) {
return;
}
View keyboard = (View) edit.getTag(TAG_ID);
if (keyboard.getParent() != null) {
((ViewGroup) keyboard.getParent()).removeView(keyboard);
}
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
((InputMethodManager) getReactApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE)).showSoftInput(edit, InputMethodManager.SHOW_IMPLICIT);
}
});
}
});
}
@ReactMethod
public void hideKeyboard(final int tag) {
UiThreadUtil.runOnUiThread(new Runnable() {
@Override
public void run() {
final ReactEditText edit = getEditById(tag);
if (edit == null) {
return;
}
View keyboard = (View) edit.getTag(TAG_ID);
if (keyboard.getParent() != null) {
((ViewGroup) keyboard.getParent()).removeView(keyboard);
}
}
});
}
}
19
Source : ReactActivity.java
with MIT License
from bevkoski
with MIT License
from bevkoski
public clreplaced ReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
private static final String REACT_MODULE_NAME = "TheNativeParts";
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
List<ReactPackage> packages = new ArrayList<>();
packages.add(new MainReactPackage());
packages.add(new CommunicationPackage());
packages.add(new CounterViewPackage());
mReactRootView = new ReactRootView(ReactActivity.this);
mReactInstanceManager = ReactInstanceManager.builder().setApplication(getApplication()).setBundlereplacedetName("index.android.bundle").setJSMainModulePath("index.android").addPackages(packages).setUseDeveloperSupport(BuildConfig.DEBUG).setInitialLifecycleState(LifecycleState.RESUMED).build();
mReactRootView.startReactApplication(mReactInstanceManager, REACT_MODULE_NAME, null);
setContentView(mReactRootView);
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause(ReactActivity.this);
}
}
@Override
protected void onResume() {
super.onResume();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(ReactActivity.this, ReactActivity.this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy(ReactActivity.this);
}
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
}
19
Source : ReactNativeIntents.java
with MIT License
from airbnb
with MIT License
from airbnb
static Bundle getSharedElementOptionsBundle(Activity activity, Intent intent, @Nullable ReadableMap options) {
ViewGroup transitionGroup = null;
if (activity instanceof ReactInterface && options != null && options.hasKey(SHARED_ELEMENT_TRANSITION_GROUP_OPTION)) {
ReactRootView reactRootView = ((ReactInterface) activity).getReactRootView();
transitionGroup = ViewUtils.findViewGroupWithTag(reactRootView, R.id.react_shared_element_group_id, options.getString(SHARED_ELEMENT_TRANSITION_GROUP_OPTION));
}
if (transitionGroup == null) {
// Even though there is no transition group, we want the activity options to include a scene
// transition so that we can postpone the enter transition.
// noinspection unchecked
return ActivityOptionsCompat.makeSceneTransitionAnimation(activity).toBundle();
} else {
ReactNativeUtils.setIsSharedElementTransition(intent);
return AutoSharedElementCallback.getActivityOptionsBundle(activity, transitionGroup);
}
}
19
Source : ReactNativeFragmentViewGroup.java
with MIT License
from airbnb
with MIT License
from airbnb
/**
* Root ViewGroup for {@link ReactNativeFragment} that allows it to get KeyEvents.
*/
public clreplaced ReactNativeFragmentViewGroup extends FrameLayout {
public interface KeyListener {
boolean onKeyDown(int keyCode, KeyEvent event);
boolean onKeyUp(int keyCode, KeyEvent event);
}
@Nullable
private ReactRootView reactRootView;
@Nullable
private KeyListener keyListener;
public ReactNativeFragmentViewGroup(Context context) {
super(context);
}
public ReactNativeFragmentViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ReactNativeFragmentViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
void setKeyListener(@Nullable KeyListener keyListener) {
this.keyListener = keyListener;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean handled = super.onKeyDown(keyCode, event);
if (!handled && keyListener != null) {
handled = keyListener.onKeyDown(keyCode, event);
}
return handled;
}
void unmountReactApplicationAfterAnimation(ReactRootView reactRootView) {
this.reactRootView = reactRootView;
}
@Override
protected void onAnimationEnd() {
super.onAnimationEnd();
if (reactRootView != null) {
reactRootView.unmountReactApplication();
reactRootView = null;
}
}
}
19
Source : ReactNativeFragmentViewGroup.java
with MIT License
from airbnb
with MIT License
from airbnb
void unmountReactApplicationAfterAnimation(ReactRootView reactRootView) {
this.reactRootView = reactRootView;
}
19
Source : ReactNativeFragment.java
with MIT License
from airbnb
with MIT License
from airbnb
public clreplaced ReactNativeFragment extends Fragment implements ReactInterface, ReactNativeFragmentViewGroup.KeyListener {
private static final String TAG = ReactNativeFragment.clreplaced.getSimpleName();
private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
static final String EXTRA_REACT_MODULE_NAME = "REACT_MODULE_NAME";
static final String EXTRA_REACT_PROPS = "REACT_PROPS";
static final String EXTRA_IS_MODAL = "IS_MODAL";
private static final String ON_DISAPPEAR = "onDisappear";
private static final String ON_APPEAR = "onAppear";
private static final String INSTANCE_ID_PROP = "nativeNavigationInstanceId";
private static final String ON_BUTTON_PRESS = "onButtonPress";
private static final String INITIAL_BAR_HEIGHT_PROP = "nativeNavigationInitialBarHeight";
// TODO(lmr): put this back down when done debugging
private static final int RENDER_TIMEOUT_IN_MS = 1700;
// An incrementing ID to identify each ReactNativeActivity instance (used in `instanceId`)
private static int UUID = 1;
private ReactNavigationCoordinator reactNavigationCoordinator = ReactNavigationCoordinator.sharedInstance;
private ReactInstanceManager reactInstanceManager = reactNavigationCoordinator.getReactInstanceManager();
private final Runnable timeoutCallback = new Runnable() {
@Override
public void run() {
Log.d(TAG, "render timeout callback called");
signalFirstRenderComplete();
}
};
private String instanceId;
private boolean isSharedElementTransition;
private boolean isWaitingForRenderToFinish = false;
private float barHeight;
private ReadableMap initialConfig = ConversionUtil.EMPTY_MAP;
private ReadableMap previousConfig = ConversionUtil.EMPTY_MAP;
private ReadableMap renderedConfig = ConversionUtil.EMPTY_MAP;
private ReactNativeFragmentViewGroup contentContainer;
private ReactRootView reactRootView;
// private ReactInterfaceManager activityManager;
private final Handler handler = new Handler();
private PermissionListener permissionListener;
private AppCompatActivity activity;
private ReactToolbar toolbar;
private View loadingView;
static ReactNativeFragment newInstance(String moduleName, @Nullable Bundle props) {
ReactNativeFragment frag = new ReactNativeFragment();
Bundle args = new BundleBuilder().putString(ReactNativeIntents.EXTRA_MODULE_NAME, moduleName).putBundle(ReactNativeIntents.EXTRA_PROPS, props).toBundle();
frag.setArguments(args);
return frag;
}
static ReactNativeFragment newInstance(Bundle intentExtras) {
ReactNativeFragment frag = new ReactNativeFragment();
frag.setArguments(intentExtras);
return frag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (instanceId == null) {
if (savedInstanceState == null) {
String moduleName = getArguments().getString(ReactNativeIntents.EXTRA_MODULE_NAME);
instanceId = String.format(Locale.ENGLISH, "%1s_fragment_%2$d", moduleName, UUID++);
} else {
instanceId = savedInstanceState.getString(INSTANCE_ID_PROP);
}
}
setHasOptionsMenu(true);
Log.d(TAG, "onCreate");
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated");
initReactNative();
}
private void initReactNative() {
if (reactRootView != null || getView() == null) {
return;
}
if (!isSuccessfullyInitialized()) {
// TODO(lmr): need a different way of doing this
// TODO(lmr): move to utils
reactInstanceManager.addReactInstanceEventListener(new ReactInstanceManager.ReactInstanceEventListener() {
@Override
public void onReactContextInitialized(ReactContext context) {
reactInstanceManager.removeReactInstanceEventListener(this);
handler.post(new Runnable() {
@Override
public void run() {
onAttachWithReactContext();
}
});
}
});
} else {
onAttachWithReactContext();
// in this case, we end up waiting for the first render to complete
// doing the transition. If this never happens for some reason, we are going to push
// anyway in 250ms. The handler should get canceled + called sooner though (it's za race).
isWaitingForRenderToFinish = true;
handler.postDelayed(new Runnable() {
@Override
public void run() {
Log.d(TAG, "render timeout callback called");
startPostponedEnterTransition();
}
}, RENDER_TIMEOUT_IN_MS);
}
// activityManager = new ReactInterfaceManager(this);
reactNavigationCoordinator.registerComponent(this, instanceId);
}
private void onAttachWithReactContext() {
Log.d(TAG, "onCreateWithReactContext");
if (getView() == null) {
return;
}
loadingView.setVisibility(View.GONE);
if (!isSuccessfullyInitialized()) {
// TODO(lmr): should we make this configurable?
// ReactNativeUtils.showAlertBecauseChecksFailed(getActivity(), null);
return;
}
String moduleName = getArguments().getString(ReactNativeIntents.EXTRA_MODULE_NAME);
Bundle props = getArguments().getBundle(ReactNativeIntents.EXTRA_PROPS);
if (props == null) {
props = new Bundle();
}
props.putString(INSTANCE_ID_PROP, instanceId);
if (reactRootView == null) {
ViewStub reactViewStub = (ViewStub) getView().findViewById(R.id.react_root_view_stub);
reactRootView = (ReactRootView) reactViewStub.inflate();
}
getImplementation().reconcileNavigationProperties(this, getToolbar(), activity.getSupportActionBar(), ConversionUtil.EMPTY_MAP, renderedConfig, true);
barHeight = getImplementation().getBarHeight(this, getToolbar(), activity.getSupportActionBar(), renderedConfig, true);
reactRootView.startReactApplication(reactInstanceManager, moduleName, props);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
postponeEnterTransition();
View v = inflater.inflate(R.layout.fragment_react_native, container, false);
toolbar = (ReactToolbar) v.findViewById(R.id.toolbar);
// TODO(lmr): should we make the "loading" XML configurable?
loadingView = v.findViewById(R.id.loading_view);
contentContainer = (ReactNativeFragmentViewGroup) v.findViewById(R.id.content_container);
contentContainer.setKeyListener(this);
activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Activity activity = ReactNativeFragment.this.getActivity();
if (activity instanceof ScreenCoordinatorComponent) {
((ScreenCoordinatorComponent) activity).getScreenCoordinator().onBackPressed();
} else {
activity.onBackPressed();
}
}
});
String moduleName = getArguments().getString(EXTRA_REACT_MODULE_NAME);
Log.d(TAG, "onCreateView " + moduleName);
initialConfig = reactNavigationCoordinator.getInitialConfigForModuleName(moduleName);
// for reconciliation, we save this in "renderedConfig" until the real one comes down
renderedConfig = initialConfig;
if (initialConfig.hasKey("screenColor")) {
int backgroundColor = initialConfig.getInt("screenColor");
// TODO(lmr): do we need to create a style for this?...
// if (backgroundColor == Color.TRANSPARENT) {
// // This needs to happen before setContentView gets called
// setTheme(R.style.Theme_Airbnb_ReactTranslucent);
// }
}
return v;
}
@Override
public void postponeEnterTransition() {
super.postponeEnterTransition();
Log.d(TAG, "postponeEnterTransition");
getActivity().supportPostponeEnterTransition();
}
@Override
public void startPostponedEnterTransition() {
super.startPostponedEnterTransition();
Log.d(TAG, "startPostponeEnterTransition");
if (getActivity() != null) {
getActivity().supportStartPostponedEnterTransition();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// activityManager.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(INSTANCE_ID_PROP, instanceId);
}
@Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
if (!enter) {
// React Native will flush the UI cache as soon as we unmount it. This will cause the view to
// disappear unless we delay it until after the fragment animation.
if (transit == FragmentTransaction.TRANSIT_NONE && nextAnim == 0) {
reactRootView.unmountReactApplication();
} else {
contentContainer.unmountReactApplicationAfterAnimation(reactRootView);
}
reactRootView = null;
}
if (getActivity() instanceof ScreenCoordinatorComponent) {
ScreenCoordinator screenCoordinator = ((ScreenCoordinatorComponent) getActivity()).getScreenCoordinator();
if (screenCoordinator != null) {
// In some cases such as TabConfig, the screen may be loaded before there is a screen
// coordinator but it doesn't live inside of any back stack and isn't visible.
return screenCoordinator.onCreateAnimation(transit, enter, nextAnim);
}
}
return null;
}
@Override
public void onPause() {
super.onPause();
emitEvent(ON_DISAPPEAR, null);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume");
updateBarHeightIfNeeded();
emitEvent(ON_APPEAR, null);
}
@Override
public void onDestroyView() {
Log.d(TAG, "onDestroyView");
super.onDestroyView();
reactNavigationCoordinator.unregisterComponent(instanceId);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (/* BuildConfig.DEBUG && */
keyCode == KeyEvent.KEYCODE_MENU) {
// TODO(lmr): disable this in prod
reactInstanceManager.getDevSupportManager().showDevOptionsDialog();
return true;
}
if (keyCode == 0) {
// this is the "backtick"
// TODO(lmr): disable this in prod
reactInstanceManager.getDevSupportManager().showDevOptionsDialog();
return true;
}
if (mDoubleTapReloadRecognizer.didDoubleTapR(keyCode, activity.getCurrentFocus())) {
reactInstanceManager.getDevSupportManager().handleReloadJS();
return true;
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (permissionListener != null && permissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) {
permissionListener = null;
}
}
@Override
public boolean isDismissible() {
return reactNavigationCoordinator.getDismissCloseBehavior(this);
}
public void dismiss() {
Intent intent = new Intent().putExtra(EXTRA_IS_DISMISS, isDismissible());
getActivity().setResult(Activity.RESULT_OK, intent);
getActivity().finish();
}
@Override
public String getInstanceId() {
return instanceId;
}
@Override
public ReactRootView getReactRootView() {
return reactRootView;
}
@Override
public ReactToolbar getToolbar() {
return toolbar;
}
@Override
public void signalFirstRenderComplete() {
Log.d(TAG, "signalFirstRenderComplete");
startPostponedEnterTransition();
}
@Override
public void notifySharedElementAddition() {
Log.d(TAG, "notifySharedElementAddition");
if (isWaitingForRenderToFinish && !ReactNativeUtils.isSharedElementTransition(getActivity())) {
// if we are receiving a sharedElement and we have postponed the enter transition,
// we want to cancel any existing handler and create a new one.
// This is effectively debouncing the call.
handler.removeCallbacksAndMessages(timeoutCallback);
handler.post(new Runnable() {
@Override
public void run() {
signalFirstRenderComplete();
}
});
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
ReactToolbar toolbar = getToolbar();
if (toolbar != null) {
// 0 will prevent menu from getting inflated, since we are inflating manually
toolbar.onCreateOptionsMenu(0, menu, inflater);
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
getImplementation().prepareOptionsMenu(this, getToolbar(), null, menu, this.previousConfig, this.renderedConfig);
super.onPrepareOptionsMenu(menu);
}
private boolean isSuccessfullyInitialized() {
return reactNavigationCoordinator.isSuccessfullyInitialized();
}
private NavigationImplementation getImplementation() {
return reactNavigationCoordinator.getImplementation();
}
public void emitEvent(String eventName, Object object) {
if (isSuccessfullyInitialized()) {
String key = String.format(Locale.ENGLISH, "NativeNavigationScreen.%s.%s", eventName, instanceId);
maybeEmitEvent(reactInstanceManager.getCurrentReactContext(), key, object);
}
}
private void reconcileNavigationProperties() {
getImplementation().reconcileNavigationProperties(this, getToolbar(), null, this.previousConfig, this.renderedConfig, false);
}
@Override
public void receiveNavigationProperties(ReadableMap properties) {
this.previousConfig = this.renderedConfig;
this.renderedConfig = ConversionUtil.combine(this.initialConfig, properties);
reconcileNavigationProperties();
updateBarHeightIfNeeded();
}
private void updateBarHeightIfNeeded() {
float newHeight = getImplementation().getBarHeight(this, getToolbar(), activity.getSupportActionBar(), renderedConfig, false);
if (newHeight != barHeight) {
barHeight = newHeight;
emitEvent("onBarHeightChanged", barHeight);
}
}
@TargetApi(Build.VERSION_CODES.M)
public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
permissionListener = listener;
requestPermissions(permissions, requestCode);
}
}
18
Source : ScriptLoadUtil.java
with MIT License
from smallnew
with MIT License
from smallnew
public static void setJsModuleName(ReactRootView rootView, String moduleName) {
try {
Field field = ReactRootView.clreplaced.getDeclaredField("mJSModuleName");
field.setAccessible(true);
field.set(rootView, moduleName);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
18
Source : PersonalInfoActivity.java
with MIT License
from qunarcorp
with MIT License
from qunarcorp
/**
* Created by xinbo.wang on 2015/3/24.
*/
public clreplaced PersonalInfoActivity extends SwipeBackActivity implements IMyProfileView, IPersonalInfoView, ICheckFriendsView, IGravatarView, ICommentView, PermissionCallback, View.OnClickListener, OnMenuItemClickListener, DefaultHardwareBackBtnHandler {
public static final int REQUEST_GRANT_CAMERA = PermissionDispatcher.getRequestCode();
public static final int REQUEST_GRANT_LOCAL = PermissionDispatcher.getRequestCode();
public static final int REQUEST_GRANT_CALL = PermissionDispatcher.getRequestCode();
public static final String JID = "jid";
public static final String IS_HIDE_BTN = "isHideBtn";
public static final String REAL_USER = "realUser";
public static final String HOT_LINE = "hotLine";
public static final String TAG = "PersonalInfoActivity";
// 头像
SimpleDraweeView user_gravatar;
// 名称
TextView nickname;
// 签名
TextView signature;
// 用户id
TextView user_id;
// 部门
TextView tv_organizational_structure;
// 查看电话
TextView phonenumberCheck;
// 添加好友
TextView add_buddy;
// 发送消息
TextView send_message;
// 评论
RelativeLayout comment_txt;
// 手机号框
RelativeLayout phone_layout;
// rn卡片
ReactRootView mrn;
LinearLayout ll_3;
// 备注
LinearLayout remark_layout;
TextView remark_text;
// SimpleDraweeView user_gravatar;
// LinearLayout ll_dept, bottom_container, ll_markup_container, ll_bottom;
// RelativeLayout rl_header;
// TextView user_id, dept_name, sign;
// TextView operation_btn, cloud_record_of_chat, dial, tv_markup;
// TextView my_qrcode;
// TextView comment_txt;
ProgressDialog progressDialog;
HandlePersonalEvent handlePersonalEvent = new HandlePersonalEvent();
boolean isHideBtn;
String jid;
// 热线的真实用户
String realUser;
String mood;
// 默认为0
String hotLine;
private String fullName;
boolean isFriend;
IPersonalInfoPresenter personalInfoPresenter;
IEditMyProfilePresenter editMyProfilePresenter;
ReactInstanceManager mReactInstanceManager;
private String selGravatarPath;
AlertDialog mDialog;
String markup;
// 备注
String markupName;
@Override
public void responsePermission(int requestCode, boolean granted) {
if (!granted)
return;
if (requestCode == REQUEST_GRANT_CAMERA) {
changeGravantarFromCamera();
} else if (requestCode == REQUEST_GRANT_LOCAL) {
changeGravantarFromLocal();
} else if (requestCode == REQUEST_GRANT_CALL) {
OpsAPI.getUserMobilePhoneNumber(CurrentPreference.getInstance().getUserid(), QtalkStringUtils.parseLocalpart(jid), new ProtocolCallback.UnitCallback<GeneralJson>() {
@Override
public void onCompleted(final GeneralJson generalJson) {
getHandler().post(new Runnable() {
@Override
public void run() {
int code;
try {
code = (int) Double.parseDouble(generalJson.errcode.toString());
} catch (Exception e) {
LogUtil.e(TAG, "ERROR", e);
code = -1;
}
if (code != 0) {
Toast.makeText(PersonalInfoActivity.this, generalJson.msg, Toast.LENGTH_SHORT).show();
} else if (generalJson.data == null) {
Toast.makeText(PersonalInfoActivity.this, R.string.atom_ui_get_phone_deny, Toast.LENGTH_SHORT).show();
} else {
Intent mIntent = new Intent(Intent.ACTION_DIAL);
mIntent.setData(Uri.parse("tel:" + generalJson.data.get("phone")));
startActivity(mIntent);
}
}
});
}
@Override
public void onFailure(String errMsg) {
getHandler().post(new Runnable() {
@Override
public void run() {
Toast.makeText(PersonalInfoActivity.this, R.string.atom_ui_tip_check_network, Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
@Override
public void onCreate(Bundle saveInstancedState) {
super.onCreate(saveInstancedState);
setContentView(R.layout.atom_ui_activity_personal_buddy_info);
bindViews();
injectExtras(getIntent());
personalInfoPresenter = PersonalInfoFactory.getPersonalPresenter();
editMyProfilePresenter = new EditMyProfilePresenter();
initViews();
EventBus.getDefault().register(handlePersonalEvent);
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
injectExtras(intent);
}
private void injectExtras(Intent intent) {
Bundle extras_ = intent.getExtras();
if (extras_ != null) {
if (extras_.containsKey(JID)) {
jid = extras_.getString(JID);
}
if (extras_.containsKey(IS_HIDE_BTN)) {
isHideBtn = extras_.getBoolean(IS_HIDE_BTN);
}
if (extras_.containsKey(REAL_USER)) {
realUser = extras_.getString(REAL_USER);
}
if (extras_.containsKey(HOT_LINE)) {
hotLine = extras_.getString(HOT_LINE);
} else {
hotLine = "0";
}
}
}
private void bindViews() {
ll_3 = (LinearLayout) findViewById(R.id.ll_3);
user_gravatar = (com.facebook.drawee.view.SimpleDraweeView) findViewById(R.id.user_gravatar);
user_id = (TextView) findViewById(R.id.user_id);
tv_organizational_structure = (TextView) findViewById(R.id.tv_organizational_structure);
nickname = (TextView) findViewById(R.id.nickname);
signature = (TextView) findViewById(R.id.signature);
// phonenumberCheck = (TextView) findViewById(R.id.phone_number_check);
add_buddy = (TextView) findViewById(R.id.add_buddy);
send_message = (TextView) findViewById(R.id.send_message);
comment_txt = (RelativeLayout) findViewById(R.id.rl_3);
// phone_layout = (RelativeLayout) findViewById(R.id.phone_layout);
// mrn = (ReactRootView) findViewById(R.id.mrn);
// tv_markup.setOnClickListener(this);
add_buddy.setOnClickListener(this);
send_message.setOnClickListener(this);
// phonenumberCheck.setOnClickListener(this);
remark_layout = (LinearLayout) findViewById(R.id.remark_layout);
remark_layout.setOnClickListener(this);
remark_text = (TextView) findViewById(R.id.remark_text);
}
void initViews() {
QtNewActionBar actionBar = (QtNewActionBar) this.findViewById(R.id.my_action_bar);
actionBar.setBackgroundResource(R.drawable.atom_ui_gradient_linear_actionbar_selector);
setNewActionBar(actionBar);
// actionBar.getLeftButton().setBackground(null);
personalInfoPresenter.setGravatarView(this);
personalInfoPresenter.setPersonalInfoView(this);
personalInfoPresenter.setCommentView(this);
editMyProfilePresenter.setPersonalInfoView(this);
markupName = ConnectionUtil.getInstance().getMarkupNameById(jid);
if (CommonConfig.isQtalk) {
//
// phone_layout.setVisibility(View.VISIBLE);
} else {
// phone_layout.setVisibility(View.GONE);
//
}
if (isHideBtn) {
// send_message.setVisibility(View.GONE);
add_buddy.setVisibility(View.GONE);
} else {
if (!TextUtils.isEmpty(jid)) {
if (jid.equals(CurrentPreference.getInstance().getPreferenceUserId())) {
send_message.setVisibility(View.GONE);
add_buddy.setVisibility(View.GONE);
comment_txt.setVisibility(View.GONE);
remark_layout.setVisibility(View.GONE);
// // CurrentPreference.getInstance().getFullName();
// // CurrentPreference.getInstance().getPreferenceUserId();
// setSignView();
// sign.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.atom_ui_edit, 0);
// isHideBtn = true;
// comment_txt.setVisibility(View.GONE);
// cloud_record_of_chat.setVisibility(View.GONE);
// bottom_container.setVisibility(View.VISIBLE);
// ll_markup_container.setVisibility(View.GONE);
// initProgressDialog();
}
} else {
// setActionBarRightIcon(R.string.atom_ui_new_more);
// final PopupMenu menu = new PopupMenu(PersonalInfoActivity.this, actionBar.getRightIcon());
// menu.inflate(R.menu.atom_ui_menu_personal);
// menu.setOnMenuItemClickListener(PersonalInfoActivity.this);
// setActionBarRightIconClick(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (isFriend) {
// menu.getMenu().findItem(R.id.menu_friend_ops).setVisible(false);
// menu.getMenu().findItem(R.id.menu_del_friend).setVisible(true);
// } else {
// menu.getMenu().findItem(R.id.menu_friend_ops).setVisible(true);
// menu.getMenu().findItem(R.id.menu_del_friend).setVisible(false);
// }
// menu.show();
// }
// });
}
}
//
// if (isHideBtn) {
//
// ll_bottom.setVisibility(View.GONE);
// } else {
// final ImageView imageView = new ImageView(this);
// imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
// imageView.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDimensionPixelSize(R.dimen.atom_ui_icon_size)
// , getResources().getDimensionPixelSize(R.dimen.atom_ui_icon_size)));
// imageView.setImageResource(R.drawable.atom_ui_more);
// actionBar.getRightContainer().addView(imageView);
//
// imageView.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// if (isFriend) {
// menu.getMenu().findItem(R.id.menu_friend_ops).setVisible(false);
// menu.getMenu().findItem(R.id.menu_del_friend).setVisible(true);
// } else {
// menu.getMenu().findItem(R.id.menu_friend_ops).setVisible(true);
// menu.getMenu().findItem(R.id.menu_del_friend).setVisible(false);
// }
// menu.show();
// }
// });
user_gravatar.setOnClickListener(this);
if (!CommonConfig.isQtalk) {
// 隐藏组织架构 隐藏评论 隐藏打电话
// ll_dept.setVisibility(View.GONE);
// comment_txt.setVisibility(View.GONE);
// findViewById(R.id.v_vertical_line).setVisibility(View.GONE);
// dial.setVisibility(View.GONE);
}
}
@Override
protected void onPause() {
super.onPause();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause(this);
}
}
@Override
public void onResume() {
super.onResume();
if (!isHideBtn) {
// 判断是不是好友 或者是在不在组织架构里判断是不是可以发消息逻辑 目前不需要这个判断 都可以发
((ICheckFriendPresenter) personalInfoPresenter).checkFriend();
}
personalInfoPresenter.loadPersonalInfo();
editMyProfilePresenter.loadMood();
remark_text.setText(editMyProfilePresenter.getMarkNames());
if (QtalkNavicationService.getInstance().getNavConfigResult().ops != null && !TextUtils.isEmpty(QtalkNavicationService.getInstance().getNavConfigResult().ops.host) && !TextUtils.isEmpty(QtalkNavicationService.getInstance().getNavConfigResult().ops.checkversion) && !TextUtils.isEmpty(QtalkNavicationService.getInstance().getNavConfigResult().ops.conf)) {
// TODO 暂时注释掉
// Bundle bundle = getDefaultBundle();
// mReactInstanceManager = QtalkCardRNViewInstanceManager.getInstanceManager(getApplication());
// if(mrn!=null){
// mrn.unmountReactApplication();
// }
// mrn = new ReactRootView(this);
// mrn.startReactApplication(mReactInstanceManager,QtalkCardRNViewInstanceManager.MODULE,bundle);
// ll_3.removeAllViews();
// ll_3.addView(mrn);
// if (mReactInstanceManager != null) {
// mReactInstanceManager.onHostResume(this, this);
// }
} else {
ll_3.setVisibility(View.GONE);
}
}
void restartChat() {
Intent intent = new Intent(this, PbChatActivity.clreplaced);
intent.putExtra("jid", jid);
intent.putExtra("isFromChatRoom", false);
intent.putExtra("realJid", TextUtils.isEmpty(realUser) ? jid : realUser);
intent.putExtra("chatType", hotLine);
startActivity(intent);
finish();
}
@Override
public void onStart() {
super.onStart();
}
// 更改群名称
void markupName() {
if (TextUtils.isEmpty(jid))
return;
View contentView = LayoutInflater.from(this).inflate(R.layout.atom_ui_dialog_change_group_name, null);
final EditText et = (EditText) contentView.findViewById(R.id.et_group_name);
et.setText(markup);
new AlertDialog.Builder(this).setreplacedle(R.string.atom_ui_common_markup).setView(contentView).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (et.getText().length() > 10) {
Toast.makeText(PersonalInfoActivity.this, R.string.atom_ui_tip_remark_toolong, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(et.getText())) {
Toast.makeText(PersonalInfoActivity.this, R.string.atom_ui_tip_remark_null, Toast.LENGTH_SHORT).show();
return;
}
String markup = et.getText().toString();
// tv_markup.setText(markup);
}
}).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
// 更改备注
void markupPersonalName() {
if (TextUtils.isEmpty(jid)) {
return;
}
final EditText et = new EditText(this);
et.setText(markupName);
new AlertDialog.Builder(this).setreplacedle(R.string.atom_ui_common_markup).setView(et).setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (et.getText().length() > 10) {
Toast.makeText(PersonalInfoActivity.this, R.string.atom_ui_tip_remark_toolong, Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(et.getText())) {
Toast.makeText(PersonalInfoActivity.this, R.string.atom_ui_tip_remark_null, Toast.LENGTH_SHORT).show();
return;
}
markupName = et.getText().toString();
editMyProfilePresenter.updateMarkupName();
}
}).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
}
void my_qrcode() {
if (!TextUtils.isEmpty(jid)) {
Intent intent = new Intent(this, QRActivity.clreplaced);
intent.putExtra("qrString", Constants.Config.QR_SCHEMA + "://user?id=" + jid);
startActivity(intent);
}
}
void cloud_record_of_chat() {
if (!TextUtils.isEmpty(fullName)) {
Intent intent = new Intent(this, CloudChatRecordActivity.clreplaced);
intent.putExtra("fullName", fullName);
intent.putExtra("isFromGroup", false);
intent.putExtra("toId", jid);
startActivity(intent);
}
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(handlePersonalEvent);
super.onDestroy();
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostDestroy();
}
if (mrn != null) {
mrn.unmountReactApplication();
}
}
@Override
public void onBackPressed() {
if (mReactInstanceManager != null) {
mReactInstanceManager.onBackPressed();
} else {
super.onBackPressed();
}
}
@Override
public void setDeptName(final String deptName) {
if (TextUtils.isEmpty(deptName))
return;
getHandler().post(new Runnable() {
@Override
public void run() {
tv_organizational_structure.setText(deptName);
// dept_name.setText(deptName);
}
});
}
@Override
public void setJid(final String jid) {
if (TextUtils.isEmpty(jid))
return;
this.jid = jid;
getHandler().post(new Runnable() {
@Override
public void run() {
user_id.setText(QtalkStringUtils.parseLocalpart(jid));
}
});
}
@Override
public SimpleDraweeView getImagetView() {
return user_gravatar;
}
@Override
public void setNickName(final String nick) {
if (TextUtils.isEmpty(nick))
return;
fullName = nick;
getHandler().post(new Runnable() {
@Override
public void run() {
nickname.setText(nick);
// myActionBar.getreplacedleTextview().setText(nick);
setActionBarreplacedle(nick);
}
});
}
@Override
public String getJid() {
return jid;
}
@Override
public String getMood() {
return mood;
}
@Override
public void setMood(final String m) {
getHandler().post(new Runnable() {
@Override
public void run() {
if (TextUtils.isEmpty(m)) {
signature.setText(R.string.atom_ui_tip_no_sign);
} else {
signature.setText(Html.fromHtml(m));
}
}
});
}
@Override
public String getMarkup() {
return markupName;
}
@Override
public void setMarkup(final boolean isScuess) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(PersonalInfoActivity.this, isScuess ? R.string.atom_ui_tip_save_success : R.string.atom_ui_tip_operation_failed, Toast.LENGTH_SHORT).show();
if (isScuess)
remark_text.setText(markupName);
}
});
}
@Override
public void setUpdateResult(final boolean result) {
if (CommonConfig.isQtalk) {
getHandler().post(new Runnable() {
@Override
public void run() {
selGravatarPath = "";
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
if (result) {
personalInfoPresenter.loadGravatar(true);
EventBus.getDefault().post(new EventBusEvent.GravantarChanged());
}
Toast.makeText(PersonalInfoActivity.this, result ? getString(R.string.atom_ui_tip_gravantar_update_success) : getString(R.string.atom_ui_tip_gravantar_update_failure), Toast.LENGTH_LONG).show();
}
});
}
}
@Override
public void setLargeGravatarInfo(String url, String thumbPath) {
Intent intent = new Intent(this, ImageBrowersingActivity.clreplaced);
intent.putExtra(Constants.BundleKey.IMAGE_URL, url);
intent.putExtra(Constants.BundleKey.IMAGE_ON_LOADING, thumbPath);
int[] location = new int[2];
user_gravatar.getLocationOnScreen(location);
intent.putExtra("left", location[0]);
intent.putExtra("top", location[1]);
intent.putExtra("height", user_gravatar.getHeight());
intent.putExtra("width", user_gravatar.getWidth());
startActivity(intent);
}
@Override
public Context getContext() {
return this;
}
@Override
public String getGravatarPath() {
return selGravatarPath;
}
@Override
public void setCommentUrl(final String url, final String uid) {
if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(uid)) {
comment_txt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String commentUrl = url + "?u=" + CurrentPreference.getInstance().getUserid() + "&k=" + CommonConfig.verifyKey + "&t=" + uid;
Intent intent = new Intent(PersonalInfoActivity.this, QunarWebActvity.clreplaced);
intent.setData(Uri.parse(commentUrl));
PersonalInfoActivity.this.startActivity(intent);
}
});
}
}
private void initProgressDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setreplacedle(R.string.atom_ui_replacedle_update_avater);
progressDialog.setMessage(getString(R.string.atom_ui_tip_updating));
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
}
private void changeGravantarFromLocal() {
Intent intentPic = new Intent(this, PictureSelectorActivity.clreplaced);
intentPic.putExtra("isGravantarSel", true);
intentPic.putExtra("isMultiSel", false);
startActivity(intentPic);
}
private void changeGravantarFromCamera() {
Intent intentCamera = new Intent(this, ImageClipActivity.clreplaced);
startActivity(intentCamera);
}
public void showAlertDialog() {
// AlertDialog.Builder builder = new AlertDialog.Builder(PersonalInfoActivity.this);
// View view = LayoutInflater.from(PersonalInfoActivity.this).inflate(R.layout.atom_ui_dialog_change_gravatar, rl_header, false);
// TextView tv_check_large_gravtar = (TextView) view.findViewById(R.id.tv_check_large_gravtar);
// TextView tv_change_gravtar_photos = (TextView) view.findViewById(R.id.tv_change_gravtar_photos);
// TextView tv_change_gravtar_camera = (TextView) view.findViewById(R.id.tv_change_gravtar_camera);
// TextView tv_change_gravatar_prompt = (TextView) view.findViewById(R.id.tv_change_gravtar_prompt);
// tv_check_large_gravtar.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// personalInfoPresenter.showLargeGravatar();
// if (mDialog != null && mDialog.isShowing()) {
// mDialog.dismiss();
// }
// }
// });
// if(CommonConfig.isQtalk) {
// tv_change_gravtar_photos.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// PermissionDispatcher.requestPermissionWithCheck(PersonalInfoActivity.this, new int[]{PermissionDispatcher.REQUEST_WRITE_EXTERNAL_STORAGE,
// PermissionDispatcher.REQUEST_READ_EXTERNAL_STORAGE},
// PersonalInfoActivity.this, REQUEST_GRANT_LOCAL);
// if (mDialog != null && mDialog.isShowing()) {
// mDialog.dismiss();
// }
// }
// });
// tv_change_gravtar_camera.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// PermissionDispatcher.requestPermissionWithCheck(PersonalInfoActivity.this, new int[]{PermissionDispatcher.REQUEST_CAMERA},
// PersonalInfoActivity.this, REQUEST_GRANT_CAMERA);
// if (mDialog != null && mDialog.isShowing()) {
// mDialog.dismiss();
// }
// }
// });
// }
// else {
// tv_change_gravtar_photos.setVisibility(View.GONE);
// tv_change_gravtar_camera.setVisibility(View.GONE);
// tv_change_gravatar_prompt.setVisibility(View.VISIBLE);
// }
//
// builder.setView(view);
// mDialog = builder.show();
// mDialog.setCanceledOnTouchOutside(true);
}
@Override
public String getCheckedUserId() {
return jid;
}
@Override
public void setCheckResult(boolean isFriend) {
if (!TextUtils.isEmpty(jid)) {
if (jid.equals(CurrentPreference.getInstance().getPreferenceUserId())) {
send_message.setVisibility(View.GONE);
add_buddy.setVisibility(View.GONE);
}
} else {
send_message.setVisibility(View.VISIBLE);
add_buddy.setVisibility(View.VISIBLE);
}
if (isFriend) {
add_buddy.setBackgroundResource(R.drawable.atom_ui_common_button_red_select);
add_buddy.setText(R.string.atom_ui_delete_friend);
add_buddy.setTextColor(ContextCompat.getColor(this, R.color.atom_ui_white));
add_buddy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(jid)) {
// AlertDialog.Builder builder = new AlertDialog.Builder(PersonalInfoActivity.this);
commonDialog.setMessage(R.string.atom_ui_prompt_del_friend);
commonDialog.setPositiveButton(R.string.atom_ui_common_confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
IBuddyPresenter buddyPresenter = new BuddyPresenter();
buddyPresenter.setBuddyView(new DeleteBuddyView() {
@Override
public String getTargetId() {
return jid;
}
});
buddyPresenter.deleteBuddy();
Toast.makeText(PersonalInfoActivity.this, R.string.atom_ui_tip_friend_deleted, Toast.LENGTH_SHORT).show();
PersonalInfoActivity.this.finish();
}
});
commonDialog.setNegativeButton(R.string.atom_ui_common_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
commonDialog.show();
}
}
});
} else {
add_buddy.setBackgroundResource(R.drawable.atom_ui_common_button_white_select);
add_buddy.setText(R.string.atom_ui_replacedle_add_buddy);
add_buddy.setTextColor(ContextCompat.getColor(this, R.color.atom_ui_light_gray_33));
add_buddy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(PersonalInfoActivity.this, AddAuthMessageActivity.clreplaced);
intent.putExtra("jid", jid);
startActivity(intent);
finish();
}
});
}
this.isFriend = isFriend;
}
// if (item.gereplacedemId() == R.id.menu_friend_ops) {
// Intent intent = new Intent(PersonalInfoActivity.this, AddAuthMessageActivity.clreplaced);
// intent.putExtra("jid", jid);
// startActivity(intent);
// finish();
// } else if (item.gereplacedemId() == R.id.menu_del_friend) {
// if (!TextUtils.isEmpty(jid)) {
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setMessage(R.string.atom_ui_prompt_del_friend);
// builder.setPositiveButton(R.string.atom_ui_common_confirm, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// IBuddyPresenter buddyPresenter = new BuddyPresenter();
// buddyPresenter.setBuddyView(new DeleteBuddyView() {
// @Override
// public String getTargetId() {
// return jid;
// }
// });
// buddyPresenter.deleteBuddy();
// Toast.makeText(PersonalInfoActivity.this, R.string.tip_friend_deleted, Toast.LENGTH_SHORT).show();
// }
// });
// builder.setNegativeButton(R.string.atom_ui_common_cancel, new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// dialog.dismiss();
// }
// });
// builder.show();
// }
// }
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.my_qrcode) {
my_qrcode();
} else if (i == R.id.cloud_record_of_chat) {
cloud_record_of_chat();
} else if (i == R.id.tv_markup) {
markupName();
} else if (i == R.id.operation_btn) {
if (!TextUtils.isEmpty(jid)) {
restartChat();
}
} else if (i == R.id.send_message) {
if (!TextUtils.isEmpty(jid)) {
restartChat();
}
} else if (i == R.id.user_gravatar) {
if (!TextUtils.isEmpty(jid)) {
if (jid.equals(CurrentPreference.getInstance().getPreferenceUserId())) {
showAlertDialog();
} else {
personalInfoPresenter.showLargeGravatar();
}
}
} else if (i == R.id.remark_layout) {
markupPersonalName();
}
// else if (i == R.id.phone_number_check) {
// PermissionDispatcher.requestPermissionWithCheck(PersonalInfoActivity.this, new int[]{PermissionDispatcher.REQUEST_CALL},
// PersonalInfoActivity.this, REQUEST_GRANT_CALL);
// }
}
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.gereplacedemId() == R.id.menu_friend_ops) {
Intent intent = new Intent(PersonalInfoActivity.this, AddAuthMessageActivity.clreplaced);
intent.putExtra("jid", jid);
startActivity(intent);
finish();
} else if (item.gereplacedemId() == R.id.menu_del_friend) {
if (!TextUtils.isEmpty(jid)) {
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
commonDialog.setMessage(R.string.atom_ui_prompt_del_friend);
commonDialog.setPositiveButton(R.string.atom_ui_common_confirm, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
IBuddyPresenter buddyPresenter = new BuddyPresenter();
buddyPresenter.setBuddyView(new DeleteBuddyView() {
@Override
public String getTargetId() {
return jid;
}
});
buddyPresenter.deleteBuddy();
Toast.makeText(PersonalInfoActivity.this, R.string.atom_ui_tip_friend_deleted, Toast.LENGTH_SHORT).show();
PersonalInfoActivity.this.finish();
}
});
commonDialog.setNegativeButton(R.string.atom_ui_common_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
commonDialog.show();
}
}
return true;
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
clreplaced HandlePersonalEvent {
public void onEventMainThread(final EventBusEvent.GravtarGot gravtarGot) {
// if(gravtarGot.jid!=null&&gravtarGot.jid.equals(jid)) {
// BackgroundExecutor.execute(new Runnable() {
// @Override
// public void run() {
// try{
// File imageFile = Glide.with(PersonalInfoActivity.this)
// .load(gravtarGot.murl)
// .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
// .get();
// final Bitmap gravantarBg = BitmapHelper.decodeFile(imageFile.getAbsolutePath());
// if(gravantarBg!=null&&!gravantarBg.isRecycled()){
// runOnUiThread(new Runnable() {
// @Override
// public void run() {
// ImageUtils.blur(gravantarBg, rl_header);
// gravantarBg.recycle();
// }
// });
// }
// }catch (Exception e){
// e.printStackTrace();
// }
// }
// });
//
//
// }
}
public void onEventMainThread(EventBusEvent.GravanterSelected selectedFile) {
File tempFile = selectedFile.selectedFile;
if (tempFile != null && tempFile.exists()) {
progressDialog.show();
selGravatarPath = tempFile.getPath();
personalInfoPresenter.updateMyPersonalInfo();
}
}
}
public Bundle getDefaultBundle() {
Bundle bundle = new Bundle();
// TODO server prefix
Map<String, String> map = new HashMap<>();
map.put("user_id", CurrentPreference.getInstance().getUserid());
map.put("qtalk_id", QtalkStringUtils.parseId(jid));
map.put("domain", "@" + QtalkNavicationService.getInstance().getXmppdomain());
bundle.putString("user_id", CurrentPreference.getInstance().getUserid());
bundle.putString("qtalk_id", QtalkStringUtils.parseId(jid));
bundle.putString("domain", "@" + QtalkNavicationService.getInstance().getXmppdomain());
// bundle.putString("server", QtalkNavicationService.getInstance().getSimpleapiurl());
return bundle;
}
}
18
Source : UIManagerModuleTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
@Test
public void testHierarchyWithView() {
UIManagerModule uiManager = getUIManagerModule();
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = uiManager.addRootView(rootView);
int viewTag = rootTag + 1;
int subViewTag = viewTag + 1;
uiManager.createView(viewTag, ReactViewManager.REACT_CLreplaced, rootTag, JavaOnlyMap.of("collapsable", false));
uiManager.createView(subViewTag, ReactViewManager.REACT_CLreplaced, rootTag, JavaOnlyMap.of("collapsable", false));
uiManager.manageChildren(viewTag, null, null, JavaOnlyArray.of(subViewTag), JavaOnlyArray.of(0), null);
uiManager.manageChildren(rootTag, null, null, JavaOnlyArray.of(viewTag), JavaOnlyArray.of(0), null);
uiManager.onBatchComplete();
executePendingFrameCallbacks();
replacedertThat(rootView.getChildCount()).isEqualTo(1);
ViewGroup child = (ViewGroup) rootView.getChildAt(0);
replacedertThat(child.getChildCount()).isEqualTo(1);
ViewGroup grandchild = (ViewGroup) child.getChildAt(0);
replacedertThat(grandchild).isInstanceOf(ViewGroup.clreplaced);
replacedertThat(grandchild.getChildCount()).isEqualTo(0);
}
18
Source : UIManagerModuleTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
/**
* replaceduming no other views have been created, the root view will have tag 1, Text tag 2, and
* RawText tag 3.
*/
private ViewGroup createSimpleTextHierarchy(UIManagerModule uiManager, String text) {
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = uiManager.addRootView(rootView);
int textTag = rootTag + 1;
int rawTextTag = textTag + 1;
uiManager.createView(textTag, ReactTextViewManager.REACT_CLreplaced, rootTag, JavaOnlyMap.of("collapsable", false));
uiManager.createView(rawTextTag, ReactRawTextManager.REACT_CLreplaced, rootTag, JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, text, "collapsable", false));
uiManager.manageChildren(textTag, null, null, JavaOnlyArray.of(rawTextTag), JavaOnlyArray.of(0), null);
uiManager.manageChildren(rootTag, null, null, JavaOnlyArray.of(textTag), JavaOnlyArray.of(0), null);
uiManager.onBatchComplete();
executePendingFrameCallbacks();
return rootView;
}
18
Source : FabricUIManagerTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
/**
* Tests that cloned text nodes will not share measure functions
*/
@Test
public void testTextMutableClone() {
ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext());
int rootTag = mFabricUIManager.addRootView(rootView);
ReactShadowNode text = mFabricUIManager.createNode(0, ReactTextViewManager.REACT_CLreplaced, rootTag, null, randomInstanceHandle());
replacedertThat(text.isMeasureDefined()).isTrue();
ReactShadowNode textCopy = text.mutableCopy(randomInstanceHandle());
replacedertThat(textCopy.isMeasureDefined()).isTrue();
textCopy.setStyleWidth(200);
text.onBeforeLayout();
text.calculateLayout();
textCopy.onBeforeLayout();
textCopy.calculateLayout();
replacedertThat(text.getLayoutWidth()).isNotEqualTo(textCopy.getLayoutWidth());
}
18
Source : CatalystUIManagerTestCase.java
with MIT License
from hellochirag
with MIT License
from hellochirag
public void _testCenteredText(String text) {
ReactRootView rootView = new ReactRootView(getContext());
int rootTag = uiManager.addRootView(rootView);
jsModule.renderCenteredTextViewTestApplication(rootTag, text);
waitForBridgeAndUIIdle();
TextView textView = getViewByTestId(rootView, "text");
// text view should be centered
String msg = "text `" + text + "` is not centered";
replacedertTrue(msg, textView.getLeft() > 0.1);
replacedertTrue(msg, textView.getTop() > 0.1);
replacedertEquals(msg, (int) Math.ceil((inPixelRounded(200) - textView.getWidth()) * 0.5f), textView.getLeft());
replacedertEquals(msg, (int) Math.ceil((inPixelRounded(100) - textView.getHeight()) * 0.5f), textView.getTop());
}
18
Source : ReactAppTestActivity.java
with MIT License
from hellochirag
with MIT License
from hellochirag
public clreplaced ReactAppTestActivity extends FragmentActivity implements DefaultHardwareBackBtnHandler, PermissionAwareActivity {
public static final String EXTRA_IS_FABRIC_TEST = "is_fabric_test";
private static final String DEFAULT_BUNDLE_NAME = "AndroidTestBundle.js";
private static final int ROOT_VIEW_ID = 8675309;
// we need a bigger timeout for CI builds because they run on a slow emulator
private static final long IDLE_TIMEOUT_MS = 120000;
private final CountDownLatch mDestroyCountDownLatch = new CountDownLatch(1);
private CountDownLatch mLayoutEvent = new CountDownLatch(1);
@Nullable
private ReactBridgeIdleSignaler mBridgeIdleSignaler;
private ScreenshotingFrameLayout mScreenshotingFrameLayout;
@Nullable
private ReactInstanceManager mReactInstanceManager;
@Nullable
private ReactRootView mReactRootView;
private LifecycleState mLifecycleState = LifecycleState.BEFORE_RESUME;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(0, 0);
// We wrap screenshot layout in another FrameLayout in order to handle custom dimensions of the
// screenshot view set through {@link #setScreenshotDimensions}
FrameLayout rootView = new FrameLayout(this);
setContentView(rootView);
mScreenshotingFrameLayout = new ScreenshotingFrameLayout(this);
mScreenshotingFrameLayout.setId(ROOT_VIEW_ID);
rootView.addView(mScreenshotingFrameLayout);
mReactRootView = new ReactRootView(this);
Intent intent = getIntent();
if (intent != null && intent.getBooleanExtra(EXTRA_IS_FABRIC_TEST, false)) {
mReactRootView.setIsFabric(true);
}
mScreenshotingFrameLayout.addView(mReactRootView);
}
@Override
protected void onPause() {
super.onPause();
mLifecycleState = LifecycleState.BEFORE_RESUME;
overridePendingTransition(0, 0);
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostPause();
}
}
@Override
protected void onResume() {
super.onResume();
mLifecycleState = LifecycleState.RESUMED;
if (mReactInstanceManager != null) {
mReactInstanceManager.onHostResume(this, this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mDestroyCountDownLatch.countDown();
if (mReactInstanceManager != null) {
mReactInstanceManager.destroy();
mReactInstanceManager = null;
}
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
mReactRootView = null;
}
mScreenshotingFrameLayout.clean();
}
public void waitForDestroy(long timeoutMs) throws InterruptedException {
mDestroyCountDownLatch.await(timeoutMs, TimeUnit.MILLISECONDS);
}
public void loadApp(String appKey, ReactInstanceSpecForTest spec, boolean enableDevSupport) {
loadApp(appKey, spec, null, DEFAULT_BUNDLE_NAME, enableDevSupport);
}
public void loadApp(String appKey, ReactInstanceSpecForTest spec, String bundleName) {
loadApp(appKey, spec, null, bundleName, false);
}
public void resetRootViewForScreenshotTests() {
if (mReactInstanceManager != null) {
mReactInstanceManager.destroy();
mReactInstanceManager = null;
}
if (mReactRootView != null) {
mReactRootView.unmountReactApplication();
}
mReactRootView = new ReactRootView(this);
mScreenshotingFrameLayout.removeAllViews();
mScreenshotingFrameLayout.clean();
mScreenshotingFrameLayout.addView(mReactRootView);
}
public void loadApp(String appKey, ReactInstanceSpecForTest spec, @Nullable Bundle initialProps, String bundleName, boolean useDevSupport) {
loadBundle(spec, bundleName, useDevSupport);
renderComponent(appKey, initialProps);
}
public void renderComponent(String appKey) {
renderComponent(appKey, null);
}
public void renderComponent(final String appKey, @Nullable final Bundle initialProps) {
final CountDownLatch currentLayoutEvent = mLayoutEvent = new CountDownLatch(1);
runOnUiThread(new Runnable() {
@Override
public void run() {
replacedertions.replacedertNotNull(mReactRootView).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
currentLayoutEvent.countDown();
replacedertions.replacedertNotNull(mReactRootView).getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
replacedertions.replacedertNotNull(mReactRootView).startReactApplication(mReactInstanceManager, appKey, initialProps);
}
});
try {
waitForBridgeAndUIIdle();
waitForLayout(5000);
} catch (InterruptedException e) {
throw new RuntimeException("Layout never occurred for component " + appKey, e);
}
}
public void loadBundle(ReactInstanceSpecForTest spec, String bundleName, boolean useDevSupport) {
mBridgeIdleSignaler = new ReactBridgeIdleSignaler();
final ReactInstanceManagerBuilder builder = ReactTestHelper.getReactTestFactory().getReactInstanceManagerBuilder().setApplication(getApplication()).setBundlereplacedetName(bundleName);
if (!spec.getAlternativeReactPackagesForTest().isEmpty()) {
builder.addPackages(spec.getAlternativeReactPackagesForTest());
} else {
builder.addPackage(new MainReactPackage());
}
builder.addPackage(new InstanceSpecForTestPackage(spec)).setUseDeveloperSupport(useDevSupport).setBridgeIdleDebugListener(mBridgeIdleSignaler).setInitialLifecycleState(mLifecycleState).setJSIModulesPackage(new JSIModulePackage() {
@Override
public List<JSIModuleSpec> getJSIModules(final ReactApplicationContext reactApplicationContext, final JavaScriptContextHolder jsContext) {
return Arrays.<JSIModuleSpec>asList(new JSIModuleSpec() {
@Override
public Clreplaced<? extends JSIModule> getJSIModuleClreplaced() {
return UIManager.clreplaced;
}
@Override
public JSIModuleProvider getJSIModuleProvider() {
return new JSIModuleProvider() {
@Override
public FabricUIManager get() {
List<ViewManager> viewManagers = mReactInstanceManager.getOrCreateViewManagers(reactApplicationContext);
EventDispatcher eventDispatcher = reactApplicationContext.getNativeModule(UIManagerModule.clreplaced).getEventDispatcher();
FabricUIManager fabricUIManager = new FabricUIManager(reactApplicationContext, new ViewManagerRegistry(viewManagers), jsContext, eventDispatcher);
new FabricJSCBinding().installFabric(jsContext, fabricUIManager);
return fabricUIManager;
}
};
}
});
}
});
final CountDownLatch latch = new CountDownLatch(1);
runOnUiThread(new Runnable() {
@Override
public void run() {
mReactInstanceManager = builder.build();
mReactInstanceManager.onHostResume(ReactAppTestActivity.this, ReactAppTestActivity.this);
latch.countDown();
}
});
try {
latch.await(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("ReactInstanceManager never finished initializing " + bundleName, e);
}
}
private ReactInstanceManager getReactInstanceManager() {
return mReactInstanceManager;
}
public boolean waitForLayout(long millis) throws InterruptedException {
return mLayoutEvent.await(millis, TimeUnit.MILLISECONDS);
}
public void waitForBridgeAndUIIdle() {
waitForBridgeAndUIIdle(IDLE_TIMEOUT_MS);
}
public void waitForBridgeAndUIIdle(long timeoutMs) {
ReactIdleDetectionUtil.waitForBridgeAndUIIdle(replacedertions.replacedertNotNull(mBridgeIdleSignaler), getReactContext(), timeoutMs);
}
public View getRootView() {
return replacedertions.replacedertNotNull(mReactRootView);
}
public ReactContext getReactContext() {
return waitForReactContext();
}
// Because react context is created asynchronously, we may have to wait until it is available.
// It's simpler than exposing synchronosition mechanism to notify listener than react context
// creation has completed.
private ReactContext waitForReactContext() {
replacedertions.replacedertNotNull(mReactInstanceManager);
try {
while (true) {
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
if (reactContext != null) {
return reactContext;
}
Thread.sleep(100);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void postDelayed(Runnable r, int delayMS) {
getRootView().postDelayed(r, delayMS);
}
/**
* Does not ensure that this is run on the UI thread or that the UI Looper is idle like {@link
* ReactAppInstrumentationTestCase#getScreenshot()}. You probably want to use that instead.
*/
public Bitmap getCurrentScreenshot() {
return mScreenshotingFrameLayout.getLastDrawnBitmap();
}
public boolean isScreenshotReady() {
return mScreenshotingFrameLayout.isScreenshotReady();
}
public void setScreenshotDimensions(int width, int height) {
mScreenshotingFrameLayout.setLayoutParams(new FrameLayout.LayoutParams(width, height));
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
}
@Override
public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) {
}
}
17
Source : ReactTextTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
@Test
public void testTextTransformCapitalizeApplied() {
UIManagerModule uiManager = getUIManagerModule();
String testTextEntered = ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd ";
String testTextTransformed = ".Aa\tBb\t\tCc Dd Ee \r\nZz I Like To Eat Apples. \n中文Éé 我喜欢吃苹果。Awdawd ";
ReactRootView rootView = createText(uiManager, JavaOnlyMap.of("textTransform", "capitalize"), JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered));
TextView textView = (TextView) rootView.getChildAt(0);
replacedertThat(textView.getText().toString()).isEqualTo(testTextTransformed);
}
17
Source : ReactTextTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
@Test
public void testTextTransformNoneApplied() {
UIManagerModule uiManager = getUIManagerModule();
String testTextEntered = ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd ";
String testTextTransformed = testTextEntered;
ReactRootView rootView = createText(uiManager, JavaOnlyMap.of("textTransform", "none"), JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered));
TextView textView = (TextView) rootView.getChildAt(0);
replacedertThat(textView.getText().toString()).isEqualTo(testTextTransformed);
}
17
Source : ReactTextTest.java
with MIT License
from hellochirag
with MIT License
from hellochirag
@Test
public void testTextTransformLowercaseApplied() {
UIManagerModule uiManager = getUIManagerModule();
String testTextEntered = ".aa\tbb\t\tcc dd EE \r\nZZ I like to eat apples. \n中文éé 我喜欢吃苹果。awdawd ";
String testTextTransformed = ".aa\tbb\t\tcc dd ee \r\nzz i like to eat apples. \n中文éé 我喜欢吃苹果。awdawd ";
ReactRootView rootView = createText(uiManager, JavaOnlyMap.of("textTransform", "lowercase"), JavaOnlyMap.of(ReactRawTextShadowNode.PROP_TEXT, testTextEntered));
TextView textView = (TextView) rootView.getChildAt(0);
replacedertThat(textView.getText().toString()).isEqualTo(testTextTransformed);
}
See More Examples