其他分享
首页 > 其他分享> > Flutter和Android混合开发(1)

Flutter和Android混合开发(1)

作者:互联网

Android工程显示Flutter布局的界面步骤(不包含从Flutter跳转到对应的Activity的操作)。

第一步:创建Android项目;

第二步:在创建好的Android项目的名称中点击右键new-->Module-->(选中)Flutter module-->next-->finish,生成好之后先不用管Flutter;

第三步:1、在项目中的MainActivity中的布局文件中main_activity进行如下布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/frame_l"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" />

             2、创建一个类TestApp继承Application,代码如下:

public class TestApp extends Application {
    public static final String ENGINE_ID = "CACHED_FLUTTER";
    private static TestApp initApp;
    private FlutterEngine flutterEngine;

    public FlutterEngine getFlutterEngine() {
        return flutterEngine;
    }

    public static TestApp getApp() {
        return initApp;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        initApp = this;

        // Flutter合并开发初始化
        flutterEngine = new FlutterEngine(initApp);
        flutterEngine.getDartExecutor().executeDartEntrypoint(
                DartExecutor.DartEntrypoint.createDefault()
        );
        FlutterEngineCache.getInstance().put(ENGINE_ID, flutterEngine);
    }
}

        3、在配置清单AndroidManifest.xml文件中引入TestApp;顺便设置下项目的样式,在res文件夹下的themes.xml中添加如下代码去掉标题栏设置,代码如下:

<style name="NoActionBar" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <item name="android:statusBarColor" tools:targetApi="l">@color/blue</item> <!-- 设置状态栏的颜色 -->
</style>

        4、在MainActivity上配置,显示Flutter上面的布局,代码如下:

public class MainActivity extends AppCompatActivity {

    static final String TAG_ACTIVITY_TO_FLUTTER = "TAG_ACTIVITY_TO_FLUTTER";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 链接Flutter,显示Flutter界面
        FragmentManager fragmentManager = getSupportFragmentManager();
        FlutterFragment mFlutterFragment = (FlutterFragment) fragmentManager.findFragmentByTag(TAG_ACTIVITY_TO_FLUTTER);
        if (mFlutterFragment == null) {
            mFlutterFragment = FlutterFragment.withCachedEngine(TestApp.getApp().ENGINE_ID).transparencyMode(TransparencyMode.opaque).build();
            fragmentManager.beginTransaction().add(R.id.frame_l, mFlutterFragment, TAG_ACTIVITY_TO_FLUTTER).commit();
        } else {
            fragmentManager.beginTransaction().show(fragmentManager.findFragmentByTag(TAG_ACTIVITY_TO_FLUTTER)).commit();
        }
    }
}

第五步:直接运行APP(切记显示的是app,而不是main.dart)

标签:Flutter,public,TAG,ACTIVITY,Android,混合,FLUTTER,TestApp
来源: https://blog.csdn.net/kuangyingwei/article/details/112555954