com.facebook.react.bridge.UiThreadUtil Java Examples

The following examples show how to use com.facebook.react.bridge.UiThreadUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Timing.java    From react-native-GPay with MIT License 6 votes vote down vote up
@ReactMethod
public void setSendIdleEvents(final boolean sendIdleEvents) {
  synchronized (mIdleCallbackGuard) {
    mSendIdleEvents = sendIdleEvents;
  }

  UiThreadUtil.runOnUiThread(new Runnable() {
    @Override
    public void run() {
      synchronized (mIdleCallbackGuard) {
        if (sendIdleEvents) {
          setChoreographerIdleCallback();
        } else {
          clearChoreographerIdleCallback();
        }
      }
    }
  });
}
 
Example #2
Source File: InCallManagerModule.java    From react-native-incall-manager with ISC License 6 votes vote down vote up
@ReactMethod
public void setKeepScreenOn(final boolean enable) {
    Log.d(TAG, "setKeepScreenOn() " + enable);
    UiThreadUtil.runOnUiThread(new Runnable() {
        public void run() {
            Activity mCurrentActivity = getCurrentActivity();
            if (mCurrentActivity == null) {
                Log.d(TAG, "ReactContext doesn't hava any Activity attached.");
                return;
            }
            Window window = mCurrentActivity.getWindow();
            if (enable) {
                window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            } else {
                window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            }
        }
    });
}
 
Example #3
Source File: ReactIntegrationTestCase.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Timing module needs to be created on the main thread so that it gets the correct Choreographer.
 */
protected Timing createTimingModule() {
  final SimpleSettableFuture<Timing> simpleSettableFuture = new SimpleSettableFuture<Timing>();
  UiThreadUtil.runOnUiThread(
      new Runnable() {
        @Override
        public void run() {
          ReactChoreographer.initialize();
          Timing timing = new Timing(getContext(), mock(DevSupportManager.class));
          simpleSettableFuture.set(timing);
        }
      });
  try {
    return simpleSettableFuture.get(5000, TimeUnit.MILLISECONDS);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example #4
Source File: OTSessionManager.java    From opentok-react-native with MIT License 6 votes vote down vote up
@ReactMethod
public void removeSubscriber(final String streamId, final Callback callback) {

    UiThreadUtil.runOnUiThread(new Runnable() {
        @Override
        public void run() {

            String mStreamId = streamId;
            Callback mCallback = callback;
            ConcurrentHashMap<String, Subscriber> mSubscribers = sharedState.getSubscribers();
            ConcurrentHashMap<String, Stream> mSubscriberStreams = sharedState.getSubscriberStreams();
            ConcurrentHashMap<String, FrameLayout> mSubscriberViewContainers = sharedState.getSubscriberViewContainers();
            Subscriber mSubscriber = mSubscribers.get(mStreamId);
            FrameLayout mSubscriberViewContainer = mSubscriberViewContainers.get(mStreamId);
            if (mSubscriberViewContainer != null) {
                mSubscriberViewContainer.removeAllViews();
            }
            mSubscriberViewContainers.remove(mStreamId);
            mSubscribers.remove(mStreamId);
            mSubscriberStreams.remove(mStreamId);
            mCallback.invoke();

        }
    });
}
 
Example #5
Source File: RNCustomKeyboardKitModule.java    From react-native-custom-keyboard-kit with MIT License 6 votes vote down vote up
@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);
        }
      });
    }
  });
}
 
Example #6
Source File: RNCustomKeyboardKitModule.java    From react-native-custom-keyboard-kit with MIT License 6 votes vote down vote up
@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);
      }
    }
  });
}
 
Example #7
Source File: RNCustomKeyboardKitModule.java    From react-native-custom-keyboard-kit with MIT License 6 votes vote down vote up
@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);
      }
    }
  });
}
 
Example #8
Source File: RNCustomKeyboardKitModule.java    From react-native-custom-keyboard-kit with MIT License 6 votes vote down vote up
@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);
      }
    }
  });
}
 
Example #9
Source File: RNCustomKeyboardKitModule.java    From react-native-custom-keyboard-kit with MIT License 6 votes vote down vote up
@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);
      }
    }
  });
}
 
Example #10
Source File: RNCustomKeyboardKitModule.java    From react-native-custom-keyboard-kit with MIT License 6 votes vote down vote up
@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());
    }
  });
}
 
Example #11
Source File: EventDispatcher.java    From react-native-GPay with MIT License 6 votes vote down vote up
@Override
public void doFrame(long frameTimeNanos) {
  UiThreadUtil.assertOnUiThread();

  if (mShouldStop) {
    mIsPosted = false;
  } else {
    post();
  }

  Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "ScheduleDispatchFrameCallback");
  try {
    moveStagedEventsToDispatchQueue();

    if (!mHasDispatchScheduled) {
      mHasDispatchScheduled = true;
      Systrace.startAsyncFlow(
          Systrace.TRACE_TAG_REACT_JAVA_BRIDGE,
          "ScheduleDispatchFrameCallback",
          mHasDispatchScheduledCount.get());
      mReactContext.runOnJSQueueThread(mDispatchEventsRunnable);
    }
  } finally {
    Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE);
  }
}
 
Example #12
Source File: ReactIntegrationTestCase.java    From react-native-GPay with MIT License 6 votes vote down vote up
protected static void initializeJavaModule(final BaseJavaModule javaModule) {
  final Semaphore semaphore = new Semaphore(0);
  UiThreadUtil.runOnUiThread(
      new Runnable() {
        @Override
        public void run() {
          javaModule.initialize();
          if (javaModule instanceof LifecycleEventListener) {
            ((LifecycleEventListener) javaModule).onHostResume();
          }
          semaphore.release();
        }
      });
  try {
    SoftAssertions.assertCondition(
        semaphore.tryAcquire(5000, TimeUnit.MILLISECONDS),
        "Timed out initializing timing module");
  } catch (InterruptedException e) {
    throw new RuntimeException(e);
  }
}
 
Example #13
Source File: StatusBarModule.java    From react-native-GPay with MIT License 6 votes vote down vote up
@ReactMethod
public void setStyle(@Nullable final String style) {
  final Activity activity = getCurrentActivity();
  if (activity == null) {
    FLog.w(ReactConstants.TAG, "StatusBarModule: Ignored status bar change, current activity is null.");
    return;
  }

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    UiThreadUtil.runOnUiThread(
      new Runnable() {
        @TargetApi(Build.VERSION_CODES.M)
        @Override
        public void run() {
          View decorView = activity.getWindow().getDecorView();
          decorView.setSystemUiVisibility(
            "dark-content".equals(style) ? View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR : 0);
        }
      }
    );
  }
}
 
Example #14
Source File: ToastModule.java    From react-native-GPay with MIT License 6 votes vote down vote up
@ReactMethod
public void showWithGravityAndOffset(
    final String message,
    final int duration,
    final int gravity,
    final int xOffset,
    final int yOffset) {
  UiThreadUtil.runOnUiThread(
      new Runnable() {
        @Override
        public void run() {
          Toast toast = Toast.makeText(getReactApplicationContext(), message, duration);
          toast.setGravity(gravity, xOffset, yOffset);
          toast.show();
        }
      });
}
 
Example #15
Source File: HeadlessJsTaskContext.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Finish a JS task. Doesn't actually stop the task on the JS side, only removes it from the list
 * of active tasks and notifies listeners. A task can only be finished once.
 *
 * @param taskId the unique id returned by {@link #startTask}.
 */
public synchronized void finishTask(final int taskId) {
  Assertions.assertCondition(
    mActiveTasks.remove(taskId),
    "Tried to finish non-existent task with id " + taskId + ".");
  Runnable timeout = mTaskTimeouts.get(taskId);
  if (timeout != null) {
    mHandler.removeCallbacks(timeout);
    mTaskTimeouts.remove(taskId);
  }
  UiThreadUtil.runOnUiThread(new Runnable() {
    @Override
    public void run() {
      for (HeadlessJsTaskEventListener listener : mHeadlessJsTaskEventListeners) {
        listener.onHeadlessJsTaskFinish(taskId);
      }
    }
  });
}
 
Example #16
Source File: RNGoogleSigninModule.java    From google-signin with MIT License 6 votes vote down vote up
@ReactMethod
public void signIn(Promise promise) {
    if (_apiClient == null) {
        rejectWithNullClientError(promise);
        return;
    }

    final Activity activity = getCurrentActivity();

    if (activity == null) {
        promise.reject(MODULE_NAME, "activity is null");
        return;
    }
    promiseWrapper.setPromiseWithInProgressCheck(promise, "signIn");
    UiThreadUtil.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Intent signInIntent = _apiClient.getSignInIntent();
            activity.startActivityForResult(signInIntent, RC_SIGN_IN);
        }
    });
}
 
Example #17
Source File: InCallManagerModule.java    From react-native-incall-manager with ISC License 6 votes vote down vote up
private void manualTurnScreenOn() {
    Log.d(TAG, "manualTurnScreenOn()");
    UiThreadUtil.runOnUiThread(new Runnable() {
        public void run() {
            Activity mCurrentActivity = getCurrentActivity();
            if (mCurrentActivity == null) {
                Log.d(TAG, "ReactContext doesn't hava any Activity attached.");
                return;
            }
            Window window = mCurrentActivity.getWindow();
            if (lastLayoutParams != null) {
                window.setAttributes(lastLayoutParams);
            } else {
                WindowManager.LayoutParams params = window.getAttributes();
                params.screenBrightness = -1; // --- Dim to preferable one
                window.setAttributes(params);
            }
            window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        }
    });
}
 
Example #18
Source File: TouchTargetHelper.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Find touch event target view within the provided container given the coordinates provided
 * via {@link MotionEvent}.
 *
 * @param eventX the X screen coordinate of the touch location
 * @param eventY the Y screen coordinate of the touch location
 * @param viewGroup the container view to traverse
 * @param viewCoords an out parameter that will return the X,Y value in the target view
 * @param nativeViewTag an out parameter that will return the native view id
 * @return the react tag ID of the child view that should handle the event
 */
public static int findTargetTagAndCoordinatesForTouch(
    float eventX,
    float eventY,
    ViewGroup viewGroup,
    float[] viewCoords,
    @Nullable int[] nativeViewTag) {
  UiThreadUtil.assertOnUiThread();
  int targetTag = viewGroup.getId();
  // Store eventCoords in array so that they are modified to be relative to the targetView found.
  viewCoords[0] = eventX;
  viewCoords[1] = eventY;
  View nativeTargetView = findTouchTargetView(viewCoords, viewGroup);
  if (nativeTargetView != null) {
    View reactTargetView = findClosestReactAncestor(nativeTargetView);
    if (reactTargetView != null) {
      if (nativeViewTag != null) {
        nativeViewTag[0] = reactTargetView.getId();
      }
      targetTag = getTouchTargetForView(reactTargetView, viewCoords[0], viewCoords[1]);
    }
  }
  return targetTag;
}
 
Example #19
Source File: FullScreen.java    From react-native-full-screen with MIT License 6 votes vote down vote up
@ReactMethod
public void onFullScreen() {
    UiThreadUtil.runOnUiThread(
            new Runnable() {
                @Override
                public void run() {
                    getCurrentActivity().getWindow().getDecorView().setSystemUiVisibility(
                            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                                    | View.SYSTEM_UI_FLAG_IMMERSIVE
                    );
                }
            }
    );

}
 
Example #20
Source File: ReactInstanceManager.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Attach given {@param rootView} to a catalyst instance manager and start JS application using
 * JS module provided by {@link ReactRootView#getJSModuleName}. If the react context is currently
 * being (re)-created, or if react context has not been created yet, the JS application associated
 * with the provided root view will be started asynchronously, i.e this method won't block.
 * This view will then be tracked by this manager and in case of catalyst instance restart it will
 * be re-attached.
 */
@ThreadConfined(UI)
public void attachRootView(ReactRootView rootView) {
  UiThreadUtil.assertOnUiThread();
  mAttachedRootViews.add(rootView);

  // Reset view content as it's going to be populated by the application content from JS.
  rootView.removeAllViews();
  rootView.setId(View.NO_ID);

  // If react context is being created in the background, JS application will be started
  // automatically when creation completes, as root view is part of the attached root view list.
  ReactContext currentContext = getCurrentReactContext();
  if (mCreateReactContextThread == null && currentContext != null) {
    attachRootViewToInstance(rootView);
  }
}
 
Example #21
Source File: ReactInstanceManager.java    From react-native-GPay with MIT License 6 votes vote down vote up
@ThreadConfined(UI)
private void recreateReactContextInBackground(
  JavaScriptExecutorFactory jsExecutorFactory,
  JSBundleLoader jsBundleLoader) {
  Log.d(ReactConstants.TAG, "ReactInstanceManager.recreateReactContextInBackground()");
  UiThreadUtil.assertOnUiThread();

  final ReactContextInitParams initParams = new ReactContextInitParams(
    jsExecutorFactory,
    jsBundleLoader);
  if (mCreateReactContextThread == null) {
    runCreateReactContextOnNewThread(initParams);
  } else {
    mPendingReactContextInitParams = initParams;
  }
}
 
Example #22
Source File: ReactInstanceManager.java    From react-native-GPay with MIT License 6 votes vote down vote up
private void attachRootViewToInstance(
    final ReactRootView rootView) {
  Log.d(ReactConstants.TAG, "ReactInstanceManager.attachRootViewToInstance()");
  Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachRootViewToInstance");
  UIManager uiManagerModule = UIManagerHelper.getUIManager(mCurrentReactContext, rootView.getUIManagerType());
  final int rootTag = uiManagerModule.addRootView(rootView);
  rootView.setRootViewTag(rootTag);
  rootView.runApplication();
  Systrace.beginAsyncSection(
    TRACE_TAG_REACT_JAVA_BRIDGE,
    "pre_rootView.onAttachedToReactInstance",
    rootTag);
  UiThreadUtil.runOnUiThread(new Runnable() {
    @Override
    public void run() {
      Systrace.endAsyncSection(
        TRACE_TAG_REACT_JAVA_BRIDGE,
        "pre_rootView.onAttachedToReactInstance",
        rootTag);
      rootView.onAttachedToReactInstance();
    }
  });
  Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
 
Example #23
Source File: ReactInstanceManager.java    From react-native-GPay with MIT License 6 votes vote down vote up
private void tearDownReactContext(ReactContext reactContext) {
  Log.d(ReactConstants.TAG, "ReactInstanceManager.tearDownReactContext()");
  UiThreadUtil.assertOnUiThread();
  if (mLifecycleState == LifecycleState.RESUMED) {
    reactContext.onHostPause();
  }

  synchronized (mAttachedRootViews) {
    for (ReactRootView rootView : mAttachedRootViews) {
      rootView.removeAllViews();
      rootView.setId(View.NO_ID);
    }
  }

  reactContext.destroy();
  mDevSupportManager.onReactInstanceDestroyed(reactContext);
  mMemoryPressureRouter.removeMemoryPressureListener(reactContext.getCatalystInstance());
}
 
Example #24
Source File: DebugOverlayController.java    From react-native-GPay with MIT License 6 votes vote down vote up
public void setFpsDebugViewVisible(final boolean fpsDebugViewVisible) {
  UiThreadUtil.runOnUiThread(new Runnable() {
    @Override
    public void run() {
      if (fpsDebugViewVisible && mFPSDebugViewContainer == null) {
        if (!permissionCheck(mReactContext)) {
          FLog.d(ReactConstants.TAG, "Wait for overlay permission to be set");
          return;
        }
        mFPSDebugViewContainer = new FpsView(mReactContext);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
          WindowManager.LayoutParams.MATCH_PARENT,
          WindowManager.LayoutParams.MATCH_PARENT,
          WindowOverlayCompat.TYPE_SYSTEM_OVERLAY,
          WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
          PixelFormat.TRANSLUCENT);
        mWindowManager.addView(mFPSDebugViewContainer, params);
      } else if (!fpsDebugViewVisible && mFPSDebugViewContainer != null) {
        mFPSDebugViewContainer.removeAllViews();
        mWindowManager.removeView(mFPSDebugViewContainer);
        mFPSDebugViewContainer = null;
      }
    }
  });
}
 
Example #25
Source File: DevLoadingViewController.java    From react-native-GPay with MIT License 6 votes vote down vote up
public void updateProgress(final @Nullable String status, final @Nullable Integer done, final @Nullable Integer total) {
  if (!sEnabled) {
    return;
  }

  UiThreadUtil.runOnUiThread(new Runnable() {
    @Override
    public void run() {
      StringBuilder message = new StringBuilder();
      message.append(status != null ? status : "Loading");
      if (done != null && total != null && total > 0) {
        message.append(String.format(Locale.getDefault(), " %.1f%% (%d/%d)", (float) done / total * 100, done, total));
      }
      message.append("\u2026"); // `...` character
      if (mDevLoadingView != null) {
        mDevLoadingView.setText(message);
      }
    }
  });
}
 
Example #26
Source File: NativeViewHierarchyManager.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Simplified version of manageChildren that only deals with adding children views
 */
public synchronized void setChildren(
  int tag,
  ReadableArray childrenTags) {
  UiThreadUtil.assertOnUiThread();
  ViewGroup viewToManage = (ViewGroup) mTagsToViews.get(tag);
  ViewGroupManager viewManager = (ViewGroupManager) resolveViewManager(tag);

  for (int i = 0; i < childrenTags.size(); i++) {
    View viewToAdd = mTagsToViews.get(childrenTags.getInt(i));
    if (viewToAdd == null) {
      throw new IllegalViewOperationException(
        "Trying to add unknown view tag: "
          + childrenTags.getInt(i) + "\n detail: " +
          constructSetChildrenErrorMessage(
            viewToManage,
            viewManager,
            childrenTags));
    }
    viewManager.addView(viewToManage, viewToAdd, i);
  }
}
 
Example #27
Source File: RNShadowTextGradient.java    From react-native-text-gradient with MIT License 6 votes vote down vote up
private @Nullable View resolveView(int tag) {
  UiThreadUtil.assertOnUiThread();
  ReactApplicationContext context = mContext.get();

  if (context != null) {
    UIManagerModule uiManager = context.getNativeModule(UIManagerModule.class);

    NativeViewHierarchyManager manager = ReflectUtils.getFieldValue(
      ReflectUtils.getFieldValue(
        uiManager.getUIImplementation(),
        "mOperationsQueue",
        null
      ),
      "mNativeViewHierarchyManager",
      null
    );

    if (manager != null) {
      return manager.resolveView(tag);
    }
  }

  return null;
}
 
Example #28
Source File: NativeViewHierarchyManager.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Returns true on success, false on failure. If successful, after calling, output buffer will be
 * {x, y, width, height}.
 */
public synchronized void measure(int tag, int[] outputBuffer) {
  UiThreadUtil.assertOnUiThread();
  View v = mTagsToViews.get(tag);
  if (v == null) {
    throw new NoSuchNativeViewException("No native view for " + tag + " currently exists");
  }

  View rootView = (View) RootViewUtil.getRootView(v);
  // It is possible that the RootView can't be found because this view is no longer on the screen
  // and has been removed by clipping
  if (rootView == null) {
    throw new NoSuchNativeViewException("Native view " + tag + " is no longer on screen");
  }
  rootView.getLocationInWindow(outputBuffer);
  int rootX = outputBuffer[0];
  int rootY = outputBuffer[1];

  v.getLocationInWindow(outputBuffer);

  outputBuffer[0] = outputBuffer[0] - rootX;
  outputBuffer[1] = outputBuffer[1] - rootY;
  outputBuffer[2] = v.getWidth();
  outputBuffer[3] = v.getHeight();
}
 
Example #29
Source File: NativeViewHierarchyManager.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Returns the coordinates of a view relative to the window (not just the RootView
 * which is what measure will return)
 *
 * @param tag - the tag for the view
 * @param outputBuffer - output buffer that contains [x,y,width,height] of the view in coordinates
 *  relative to the device window
 */
public synchronized void measureInWindow(int tag, int[] outputBuffer) {
  UiThreadUtil.assertOnUiThread();
  View v = mTagsToViews.get(tag);
  if (v == null) {
    throw new NoSuchNativeViewException("No native view for " + tag + " currently exists");
  }

  v.getLocationOnScreen(outputBuffer);

  // We need to remove the status bar from the height.  getLocationOnScreen will include the
  // status bar.
  Resources resources = v.getContext().getResources();
  int statusBarId = resources.getIdentifier("status_bar_height", "dimen", "android");
  if (statusBarId > 0) {
    int height = (int) resources.getDimension(statusBarId);
    outputBuffer[1] -= height;
  }

  // outputBuffer[0,1] already contain what we want
  outputBuffer[2] = v.getWidth();
  outputBuffer[3] = v.getHeight();
}
 
Example #30
Source File: NativeViewHierarchyManager.java    From react-native-GPay with MIT License 6 votes vote down vote up
/**
 * Show a {@link PopupMenu}.
 *
 * @param reactTag the tag of the anchor view (the PopupMenu is displayed next to this view); this
 *        needs to be the tag of a native view (shadow views can not be anchors)
 * @param items the menu items as an array of strings
 * @param success will be called with the position of the selected item as the first argument, or
 *        no arguments if the menu is dismissed
 */
public synchronized void showPopupMenu(int reactTag, ReadableArray items, Callback success,
                                       Callback error) {
  UiThreadUtil.assertOnUiThread();
  View anchor = mTagsToViews.get(reactTag);
  if (anchor == null) {
    error.invoke("Can't display popup. Could not find view with tag " + reactTag);
    return;
  }
  mPopupMenu = new PopupMenu(getReactContextForView(reactTag), anchor);

  Menu menu = mPopupMenu.getMenu();
  for (int i = 0; i < items.size(); i++) {
    menu.add(Menu.NONE, Menu.NONE, i, items.getString(i));
  }

  PopupMenuCallbackHandler handler = new PopupMenuCallbackHandler(success);
  mPopupMenu.setOnMenuItemClickListener(handler);
  mPopupMenu.setOnDismissListener(handler);

  mPopupMenu.show();
}