这是可用的代码,用于在Flutter中显示原生Android TextView。
Main.dart
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) => MaterialApp( home: Native() );
}
class Native extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Expanded( child: AndroidView(viewType: "view1",) ),
],
),
);
}
}
MainActivity.java
package com.example.native_view_test;
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterEngine;
public class MainActivity extends FlutterActivity {
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
flutterEngine
.getPlatformViewsController()
.getRegistry()
.registerViewFactory("view1", new NativeViewFactory());
}
}
NativeViewFactory.java
package com.example.native_view_test;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Map;
import io.flutter.plugin.common.StandardMessageCodec;
import io.flutter.plugin.platform.PlatformView;
import io.flutter.plugin.platform.PlatformViewFactory;
class NativeViewFactory extends PlatformViewFactory {
NativeViewFactory() {
super(StandardMessageCodec.INSTANCE);
}
@Override
public PlatformView create(@NonNull Context context, int id, @Nullable Object args) {
final Map<String, Object> creationParams = (Map<String, Object>) args;
return new NativeView(context, id, creationParams);
}
}
NativeView.java
package com.example.native_view_test;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.widget.TextView;
import java.util.Map;
import io.flutter.plugin.platform.PlatformView;
class NativeView implements PlatformView {
private final TextView textView;
NativeView(Context context, int id, Map<String, Object> creationParams) {
textView = new TextView(context);
textView.setTextSize(42);
textView.setBackgroundColor(Color.rgb(255, 255, 255));
textView.setText("Rendered on a native Android view (id: " + id + ")");
}
@Override
public View getView() {
return textView;
}
@Override
public void dispose() {}
}