欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android JetPack Compose尝鲜~~

程序员文章站 2022-03-04 22:54:22
...

       最近下载了AndroidStudio4.0,桌面图标变成了橘黄色,有点小清新,给人焕然一新的感觉,加载界面也变了,简直不要太时尚,在微信公众号和掘金看到几篇博客,写得不错,于是也尝试了一下.

Android JetPack Compose尝鲜~~

 

1.简介:Jetpack Compose是用于构建本机Android UI的现代工具包。Jetpack Compose使用更少的代码,强大的工具和直观的Kotlin API简化并加速了Android上的UI开发。

2.下载Android Studio4.0预览版4 ,地址:https://www.androiddevtools.cn/

Android JetPack Compose尝鲜~~

3.配置 

App的build.gradle目录:

3.1
buildFeatures {
    // Enables Jetpack Compose for this module
    compose true
}
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

kotlinOptions {
    jvmTarget = "1.8"
}

3.2 Jetpack Compose工具包依赖

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.ui:ui-tooling:0.1.0-dev02'
    implementation 'androidx.ui:ui-layout:0.1.0-dev02'
    implementation 'androidx.ui:ui-material:0.1.0-dev02'
}

 4.这里有个坑说下,一定要把 minSdkVersion 设置为21,因为我新建项目的时候默认配置的是16,当时一直跑不起来,app是打叉状态,刚开始我以为没有配置启动的Activity,但是打开Manifest是有的,所以这个一下就排除了。

Android JetPack Compose尝鲜~~

5.为了验证这个我改回去试试,发现确实报错打叉状态,改回来就立马正常了截图如下:

Android JetPack Compose尝鲜~~

 

 6.项目的build.gradle配置

Android JetPack Compose尝鲜~~

 

buildscript {
    ext.kotlin_version = '1.3.60-eap-25'
    repositories {
        google()
        jcenter()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.0-alpha04'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

7.定义一个Compose函数:

class TestActivity : AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                Greeting("Android")
            }
        }
    }
@Composable
private fun Greeting(s: String) {
    Text(text = "Hello $s!")
}

Android JetPack Compose尝鲜~~

8.布局,在Compose中ui布局是分层级的,元素包含在其他元素中。在Jetpack Compose中,你可以通过从其他composable函数中调composable函数来构建UI层次结构。

Android JetPack Compose尝鲜~~

9.添加多个TextView:

Android JetPack Compose尝鲜~~

10.Android最常用的是LinearLayout ,设置android:orientation 值为vertical, 子元素就会垂直排列,那么,在Jetpack Compose 中,如何来实现垂直布局呢?看官方文档,使用column并添加样式,Column()功能使您可以垂直堆叠元素。添加Column()NewsStory()功能。默认设置直接将所有子项堆叠在一起,没有间距。该列本身放在内容视图的左上角。

Android JetPack Compose尝鲜~~

Android JetPack Compose尝鲜~~

 

 11.显示一张图片:

   先看官方文档:

Android JetPack Compose尝鲜~~

val image = +imageResource(R.mipmap.invitation_bg)
// 放在容器中,设置大小
Container(expanded = true, height = 180.dp) {
        //显示图片
        DrawImage(image)
}
12.添加间距:

// 添加垂直方向间距20dp
HeightSpacer(height = 20.dp)

 13,使用 material design设计

Android JetPack Compose尝鲜~~

Shape是Material Design 系统中的支柱之一,我们来用clip函数对图片进行圆角裁剪。 

Android JetPack Compose尝鲜~~

14.设置文字样式

通过Compose,可以轻松利用材料设计原则。应用于 MaterialTheme() 您创建的组件。还可以给Text添加多行显示等等.

Android JetPack Compose尝鲜~~

15.按钮:

DrawerButton(
    R.mipmap.invitation_bg.also { },
    label = "Home",
    isSelected = true
) {
}
@Composable
private fun DrawerButton(
    @DrawableRes icon: Int,
    label: String,
    isSelected: Boolean,
    action: () -> Unit
) {
    val textIconColor = if (isSelected) {
        +themeColor { primary }
    } else {
        (+themeColor { onSurface }).copy(alpha = 0.6f)
    }
    val backgroundColor = if (isSelected) {
        (+themeColor { primary }).copy(alpha = 0.12f)
    } else {
        +themeColor { surface }
    }

    Padding(left = 8.dp, top = 8.dp, right = 8.dp) {
        Surface(
            color = backgroundColor,
            shape = RoundedCornerShape(4.dp)
        ) {
            Button(onClick = action, style = TextButtonStyle()) {
                Row(
                    mainAxisSize = LayoutSize.Expand,
                    crossAxisAlignment = CrossAxisAlignment.Center
                ) {
                    WidthSpacer(16.dp)
                    Text(
                        text = label,
                        style = (+themeTextStyle { body2 }).copy(
                            color = textIconColor
                        )
                    )
                }
            }
        }
    }
}

16.Mainivity完整代码及最终的运行效果如下:

/**
 * 作者: njb
 * 时间: 2018/11/26  13:30
 * 描述: JetPack尝鲜
 * 来源:
 */
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewsComposeText("Android JetPack Demo")
        }
    }

    @Composable
    private fun NewsComposeText(s: String) {
        val image = +imageResource(R.mipmap.invitation_bg)
        MaterialTheme() {
            Column(
                crossAxisSize = LayoutSize.Expand,
                modifier = Spacing(16.dp)
            ) {
                // 放在容器中,设置大小
                Container(expanded = true, height = 180.dp) {
                    Clip(shape = RoundedCornerShape(10.dp)) {
                        //显示图片
                        DrawImage(image)
                    }
                }
                // 添加垂直方向间距20dp
                HeightSpacer(height = 20.dp)
                Text(text = "Hello $s!")
                Text(
                    "我是来尝鲜 JetPack Compose 的!JetPack Compose 尝鲜 很爽,JetPack Compose 复用性又强,可以抽取很多公共组件",
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis,
                    style = (+themeTextStyle { h5 }).withOpacity(0.5f)
                )
                Text("Android JetPack 尝鲜", style = (+themeTextStyle { body1 }).withOpacity(0.5f))
                Text("不要怂就是干", style = (+themeTextStyle { body2 }).withOpacity(0.6f))

                DrawerButton(
                    R.mipmap.invitation_bg.also { },
                    label = "Home",
                    isSelected = true
                ) {
                }
            }
        }
    }
}

@Composable
private fun DrawerButton(
    @DrawableRes icon: Int,
    label: String,
    isSelected: Boolean,
    action: () -> Unit
) {
    val textIconColor = if (isSelected) {
        +themeColor { primary }
    } else {
        (+themeColor { onSurface }).copy(alpha = 0.6f)
    }
    val backgroundColor = if (isSelected) {
        (+themeColor { primary }).copy(alpha = 0.12f)
    } else {
        +themeColor { surface }
    }

    Padding(left = 8.dp, top = 8.dp, right = 8.dp) {
        Surface(
            color = backgroundColor,
            shape = RoundedCornerShape(4.dp)
        ) {
            Button(onClick = action, style = TextButtonStyle()) {
                Row(
                    mainAxisSize = LayoutSize.Expand,
                    crossAxisAlignment = CrossAxisAlignment.Center
                ) {
                    WidthSpacer(16.dp)
                    Text(
                        text = label,
                        style = (+themeTextStyle { body2 }).copy(
                            color = textIconColor
                        )
                    )
                }
            }
        }
    }
}

Android JetPack Compose尝鲜~~

参考博客:https://juejin.im/post/5dd223a9518825494f163ce0

官方网站地址:https://developer.android.google.cn/jetpack/compose/tutorial

项目demo地址:https://gitee.com/jackning_admin/JetPackComposeDemo

17.总结:感觉和flutter差不多,初学还是听有趣的,不过由于还在体验阶段,所以问题很多,小伙伴们不要着急,后面会慢慢完善,但是这并不能妨碍我们学习和体验它,声明式 UI 框架近年来飞速发展,不过我目前预览还没有成功,等周末下载官方demo看看,以后,原生UI布局,声明式可能将会是主流.欢迎小伙伴们积极参与留言,如有问题及时提出,一起学习.