Flutter 页面嵌入 Android原生 View
在Flutter中嵌入Android原生View可以通过PlatformView实现。以下是一个简单的示例:
首先,在你的Flutter项目的android
目录下的MainActivity.java
文件中,你需要创建一个新的Android View。假设我们创建一个简单的TextView
:
// MainActivity.java
import android.os.Bundle;
import android.widget.TextView;
import io.flutter.app.FlutterActivity;
import io.flutter.plugin.platform.PlatformViewFactory;
import io.flutter.plugins.flutter_plugin_android_lifecycle.FlutterAndroidLifecycle;
public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FlutterAndroidLifecycle.setApplicationLifecycle(this, getLifecycle());
// 创建一个TextView作为原生View
TextView textView = new TextView(this);
textView.setText("Hello from Android");
// 注册原生View到Flutter,这里的id是Flutter端用来识别这个View的唯一标识
FlutterViewContainerFactory flutterViewContainerFactory = new FlutterViewContainerFactory(textView);
this.registry.registerViewFactory("textView", flutterViewContainerFactory);
}
}
class FlutterViewContainerFactory extends PlatformViewFactory {
FlutterViewContainerFactory(TextView textView) {
super(textView);
}
@Override
public PlatformView create(Context context, int id, Object args) {
// 创建并返回PlatformView
TextView textView = new TextView(context);
textView.setId(id);
return new PlatformView(textView);
}
}
class PlatformView implements io.flutter.plugin.platform.PlatformView {
private final TextView textView;
PlatformView(TextView textView) {
this.textView = textView;
}
@Override
public View getView() {
return textView;
}
@Override
public void dispose() {
// 释放资源
}
}
然后,在Flutter端,你可以使用AndroidView
小部件来嵌入这个原生View:
// main.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Plugin Example'),
),
body: Center(
child: AndroidView(
viewType: 'textView', // 与Java代码中的id相对应
),
),
),
);
}
}
确保你的AndroidManifest.xml
和MainActivity.java
文件
评论已关闭