You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio创建Kotlin项目时如何选用XML模板而非Compose模板

如何创建基于XML布局的Android空Activity(无Composable函数)

方法一:新建项目时直接选择对应模板

  • 打开Android Studio,点击「New Project」
  • 在模板列表里,不要选默认的「Empty Activity」(当前版本默认带Compose),选择**「Empty Views Activity」**模板
  • 填写项目名称、包名,语言选Kotlin,点击「Finish」就能生成完全基于XML布局的项目,不会包含任何Composable代码

方法二:将已有的Compose项目改为XML布局

如果已经创建了带Compose的项目,按以下步骤修改:

  1. 重写MainActivity代码
    打开MainActivity.kt,删掉所有Compose相关代码,改成传统Activity写法:
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main) // 关联XML布局文件
    }
}
  1. 创建XML布局文件
  • 右键点击res/layout目录 → 「New」→「Layout Resource File」
  • 文件名填activity_main,根布局推荐选ConstraintLayout,点击「OK」
  • 可以在XML中添加基础UI控件,示例代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  1. 移除Compose相关依赖(可选)
    打开模块级的build.gradle文件,删除所有和Compose有关的依赖、插件配置(比如implementation "androidx.compose.ui:ui"这类条目),然后点击「Sync Now」同步项目即可

内容的提问来源于stack exchange,提问作者Abhinesh Jha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 22:07:36