React Native,本地Android模块如何在View中添加TextView

3
我正在尝试按照教程视频制作React Native在Android上的本地模块,但似乎不完整,我找不到完成它的方法。
我正在尝试显示一个正方形,并在其中传递一个文本作为prop。
但我无法在Android上在View中添加TextView。
这是我的文件。
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());
    }
}

这是我的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
    } 
}

到目前为止,我只有一个蓝色的正方形。我走对了吗?

1个回答

4

我想我已经成功地使它工作了。关键在于使用 LinearLayout,但我不知道这是否是正确的方法...

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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接