3

I am trying to make a Native Module for React Native on Android following that tutorial video but it seems incomplete and I cannot find a way to finish it.

I am trying to display a Square, and within that square, a text passed as a prop.

But I am not able to add a TextView within a View on Android.

Here is my SquarePackage.java

public class SquarePackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.<ViewManager>singletonList(new SquareManager());
    }
}

and here is my SquareManager.java

public class SquareManager extends SimpleViewManager<View> {
    public static final String REACT_CLASS = "Square";

    private View view;
    private TextView textView;

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    protected View createViewInstance(ThemedReactContext reactContext) {
        view = new View(reactContext);
        view.setBackgroundColor(Color.BLUE);
        textView = new TextView(reactContext);
        // view.addView(textView); // <-- This does not work, addView not being a method of View
        return view;
    }

    @ReactProp(name = "text")
    public void setTextProp(View view, String prop) {
        // view.setText(prop); // <-- this does not work as I cannot setText on a View
    } 
}

So far I only have a blue Square. Am I on the right way?

Kevin Amiranoff
  • 13,440
  • 11
  • 59
  • 90

1 Answers1

4

I managed to make it work I think. The trick was to use LinearLayout but I don't know if it is the right way of doing it...

public class SquareManager extends SimpleViewManager<LinearLayout> {
    public static final String REACT_CLASS = "Square";

    private LinearLayout linearLayout;
    private TextView textView;

    @Override
    public String getName() {
        return REACT_CLASS;
    }

    @Override
    protected LinearLayout createViewInstance(ThemedReactContext reactContext) {
      linearLayout = new LinearLayout(reactContext);
      linearLayout.setBackgroundColor(Color.BLUE);
      textView = new TextView(reactContext);
      textView.setTextColor(Color.WHITE);
      linearLayout.addView(textView);
      return linearLayout;
}

    @ReactProp(name = "text")
    public void setTextProp(View view, String prop) {
         textView.setText(prop);
    }
}
Kevin Amiranoff
  • 13,440
  • 11
  • 59
  • 90