Android Jetpack Compose学习(一)—— Jetpack compose入门

Jetpack compose简介

Jetpack compose是Google推出的用于构建原生Android UI的一个工具包,它使用了大量的Kotlin语言特性,其开发方式与Flutter很类似,可以在很大程度上简化Android UI的开发。

目前(2021年5月31日)Jetpack compose的版本为Beta版,还未发布1.0正式版。

需要注意的是:只能使用Kotlin语言来做基于Jetpack compose的开发

Jetpack compose起步

目前(2021年5月31日),要在Android项目中使用Jetpack compose来开发原生UI,必须使用Android Studio Canary版本,在这里可以下载到Canary版本。

要想在Android项目中使用Jetpack compose,需要如下两个步骤(确保已经创建了基于Kotlin的Android工程):

  1. 在项目根目录下的build.gradle文件中定义compose版本:
buildscript {
    ext.kotlin_version = '1.4.31'
    ext.compose_version = '1.0.0-beta03'

    ...
}
  1. 在module根目录下的build.gradle文件中加入如下配置(注意应用的最低API级别为21):
plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'org.jetbrains.kotlin.android'     // 1
}


android {
	
	...

	defaultConfig {
		...
        minSdkVersion 21 
    }
    
	buildFeatures {           // 2
        compose true
    }

    composeOptions {        // 3
        kotlinCompilerVersion kotlin_version
        kotlinCompilerExtensionVersion compose_version
    }
}

dependencies {    // 4 引入Jetpack compose相关依赖库
	implementation "androidx.compose.ui:ui:$compose_version"
    // Tooling support (Previews, etc.)
    implementation "androidx.compose.ui:ui-tooling:$compose_version"
    // Foundation (Border, Background, Box, Image, Scroll, shapes, animations, etc.)
    implementation "androidx.compose.foundation:foundation:$compose_version"
    // Material Design
    implementation "androidx.compose.material:material:$compose_version"
    // Material design icons
    implementation "androidx.compose.material:material-icons-core:$compose_version"
    implementation "androidx.compose.material:material-icons-extended:$compose_version"
    // Integration with observables
    implementation "androidx.compose.runtime:runtime-livedata:$compose_version"
    implementation "androidx.compose.runtime:runtime-rxjava2:$compose_version"

    // UI Tests
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
	
	implementation "androidx.activity:activity-compose:1.3.0-alpha05"
}

一个最简单的Jetpack compose程序

下面的代码展示了一个最简单的使用Jetpack compose开发的UI界面:

import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.material.Text

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Text("hello world")
        }
    }
}

上面的代码运行在手机上如下图所示:
在这里插入图片描述
可以看到Jetpack compose完全抛弃了之前我们使用的XML开发布局的那一套,完全使用Kotlin代码即可开发UI了。

本篇暂时记录到此,后续会继续记录更多关于Jetpack compose的知识点。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yubo_725

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值