Flutter开发之——Android-Flutter添加到Activity,十多家大厂Android面试真题锦集干货整理
在Android项目中集成Flutter模块通常涉及以下步骤:
- 在Android项目中添加Flutter模块。
- 同步Gradle配置。
- 初始化Flutter引擎。
- 创建FlutterView并添加到Activity中。
以下是一个简化的示例代码,展示如何在现有的Android Activity中添加Flutter:
import io.flutter.embedding.android.FlutterView;
public class MainActivity extends AppCompatActivity {
private FlutterView flutterView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化FlutterView,这通常在Application类中完成,但为了简化,我们直接在Activity中做。
FlutterView.DartEntrypoint dartEntrypoint = new FlutterView.DartEntrypoint(
FlutterMain.findAppBundlePath(this), "main"
);
flutterView = new FlutterView(this, dartEntrypoint);
// 将FlutterView添加到Activity的布局中
FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
);
addContentView(flutterView, layoutParams);
}
@Override
protected void onDestroy() {
super.onDestroy();
flutterView.destroy();
}
}
确保在你的AndroidManifest.xml
中添加了必要的权限和Flutter所需的FlutterActivity
配置。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:label="My App"
android:icon="@mipmap/ic_launcher">
<!-- 其他配置 -->
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- 指定Activity的布局 -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<catego
评论已关闭