react-native android | native view visibility callback

Viewed 261

Intro

I have a simple example which uses some native view which I use in javascript code like this:

import React, { useState, useEffect } from 'react';
import { Text, Button, View } from 'react-native';

const TestApp = () => {
  const [isShowingNativeView, setIsShowingNativeView] = useState(true);

  // ... some state logic

  let contentView;
  if (isShowingNativeView) {
    contentView = <MyNativeView />;
  } else {
    contentView = <Text>Text component</Text>;
  }

  return (
    <View style={{ width: '100%', heinght: '100%' }}>
      {contentView}
    </View>
  );
}

export default TestApp;

This is how ViewManager implementation looks like:

class MyNativeViewManager(private val reactContext: ReactApplicationContext) : SimpleViewManager<MyNativeView>() {

    companion object {
        private val TAG = MyNativeViewManager::class.java.simpleName
        private val REACT_CLASS = MyNativeView::class.java.simpleName
    }

    override fun getName(): String = REACT_CLASS

    override fun createViewInstance(reactContext: ThemedReactContext): MyNativeView {
        return MyNativeView(reactContext)
    }

    override fun onDropViewInstance(view: MyNativeView) {
        Log.d(TAG, "onDropViewInstance")
        super.onDropViewInstance(view)
    }
}

And this is MyNativeView implementation:

class MyNativeView(context: Context) : GLSurfaceView(context) {

    private val TAG = MyNativeView::class.java.simpleName as String

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        Log.d(TAG, "onAttachedToWindow")
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        Log.d(TAG, "onDetachedFromWindow")
    }

    override fun onWindowVisibilityChanged(visibility: Int) {
        super.onWindowVisibilityChanged(visibility)
        Log.d(TAG, "onWindowVisibilityChanged $visibility")
    }

    override fun onDisplayHint(hint: Int) {
        super.onDisplayHint(hint)
        Log.d(TAG, "onDisplayHint $hint")
    }
}

Question

How can I get visibility callback in native code, when my view is visible or not? I have tried:

  • ViewManager.onDropViewInstance
  • ViewManager.onDetachedFromWindow
  • View.onWindowVisibilityChanged
  • View.onDisplayHint
  • View.onVisibilityChanged
  • View.onVisibilityAggregated
  • View.onStartTemporaryDetach

But none of those ones works.

Can this be achieved in the way how I expected it? Should I try another approach?

Update

This project https://github.com/ShaMan123/react-native-visibility-tracker use the same approach which I have tried and looks like it works, so maybe something related to GLSurfaceView by itself

0 Answers
Related