Java Code Examples for com.facebook.react.bridge.UiThreadUtil

The following examples show how to use com.facebook.react.bridge.UiThreadUtil. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: google-signin   Source File: RNGoogleSigninModule.java    License: MIT License 6 votes vote down vote up
@ReactMethod
public void signInSilently(Promise promise) {
    if (_apiClient == null) {
        rejectWithNullClientError(promise);
        return;
    }
    promiseWrapper.setPromiseWithInProgressCheck(promise, "signInSilently");
    UiThreadUtil.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Task<GoogleSignInAccount> result = _apiClient.silentSignIn();
            if (result.isSuccessful()) {
                // There's immediate result available.
                handleSignInTaskResult(result);
            } else {
                result.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(Task task) {
                        handleSignInTaskResult(task);
                    }
                });
            }
        }
    });
}
 
Example 2
@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 3
@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 4
@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 5
@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 6
@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
@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 8
Source Project: react-native-GPay   Source File: EventDispatcher.java    License: 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 9
Source Project: opentok-react-native   Source File: OTSessionManager.java    License: 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 10
Source Project: react-native-GPay   Source File: ReactIntegrationTestCase.java    License: 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 11
Source Project: react-native-incall-manager   Source File: InCallManagerModule.java    License: 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 12
Source Project: react-native-GPay   Source File: ReactIntegrationTestCase.java    License: 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 Project: react-native-GPay   Source File: StatusBarModule.java    License: 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 Project: react-native-GPay   Source File: ToastModule.java    License: 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 Project: react-native-GPay   Source File: HeadlessJsTaskContext.java    License: 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 Project: react-native-GPay   Source File: Timing.java    License: 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 17
Source Project: react-native-incall-manager   Source File: InCallManagerModule.java    License: 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 Project: react-native-GPay   Source File: TouchTargetHelper.java    License: 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 Project: react-native-full-screen   Source File: FullScreen.java    License: 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 Project: google-signin   Source File: RNGoogleSigninModule.java    License: 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 21
Source Project: react-native-GPay   Source File: ReactInstanceManager.java    License: 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 22
Source Project: react-native-GPay   Source File: ReactInstanceManager.java    License: 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 23
Source Project: react-native-GPay   Source File: ReactInstanceManager.java    License: 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 24
Source Project: react-native-GPay   Source File: ReactInstanceManager.java    License: 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 25
Source Project: react-native-GPay   Source File: DebugOverlayController.java    License: 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 26
Source Project: react-native-GPay   Source File: DevLoadingViewController.java    License: 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 27
Source Project: react-native-GPay   Source File: NativeViewHierarchyManager.java    License: 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 28
Source Project: react-native-text-gradient   Source File: RNShadowTextGradient.java    License: 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 29
Source Project: react-native-GPay   Source File: NativeViewHierarchyManager.java    License: 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 30
Source Project: react-native-GPay   Source File: NativeViewHierarchyManager.java    License: 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();
}