使用Qt Quick for Android 制作 Android 碎片
通过使用基于 ViewGroup 的对象,您可以在 Android UI 布局中使用QtQuickView。这里我们将使用FrameLayout。
如果你不熟悉QtQuickViewAPI,请在继续本教程之前阅读其文档。
在继续学习之前,不妨先了解一下 Qt Academy 课程:在 Android 应用程序中嵌入Qt Quick 3D 内容。
首先,使用Bottom Navigation Views Activity 模板在 Android Studio 中创建一个新项目。
- 找到你想让 QtQuickView 可见的片段或活动。这里我们使用
HomeFragment
和fragment_home.xml
。 - 在
fragment_home.xml
中创建一个 FrameLayout 并设置其id
,如下所示。<FrameLayout android:id="@+id/homeQmlFrame" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHeight_percent="0.8"/>
请注意这个 id,因为在绑定布局时需要在
HomeFragment
中引用它。 - 在 HomeFragment.kt 中,为 FrameLayout 添加导入语句:
import android.widget.FrameLayout
- 为QtQuickView和 Screen01 QML 类型添加导入,并在类中声明:
import org.qtproject.qt.android.QtQuickView import org.qtproject.example.RoboApp.RoboContent.Screen01 class HomeFragment : Fragment() { private var binding: FragmentHomeBinding? = null private lateinit var homeQmlContent: Screen01 private lateinit var homeQtQuickView: QtQuickView
- 为 QtQuickView 赋值,使用
requireActivity()
homeQtQuickView = QtQuickView(requireActivity()) homeQmlContent = Screen01()
- 如果您以编程方式创建视图、动态添加视图或在运行时更改视图,则初始化布局参数。否则,您可以跳过本节,也无需使用
params
与addView()
。val params = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
- 将视图添加到布局中:
- 在
onCreateView()
中使用视图绑定:首先在应用程序的 build.gradle.kts android 部分中添加buildFeature
部分,检查是否已启用视图绑定:buildFeatures { viewBinding = true }
然后在
onCreateView()
中添加以下内容:binding = FragmentHomeBinding.inflate( inflater, container, false) homeQtQuickView.loadContent(homeQmlContent) val root: View = binding.root binding.homeQmlFrame.addView(homeQtQuickView, params) ... return root
- 在
onCreate()
中使用findViewById()
:val qtFrame = findViewById(R.id.qtFrame) qmlFrame.addView(m_quickView, params) m_quickView.loadContent(homeQmlContent)
请参阅其他Qt Quick Android 示例中的用法。
- 在
现在,您的Qt Quick 内容将出现在您的主页片段中。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.