Jetpack Compose 快速上手

发布时间:2024年01月17日

1.Composable 注解与 Preview

package com.tiger.compose0117

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.tiger.compose0117.ui.theme.Compose0117Theme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MessageCard(name = "My Android")


        }
    }


    @Composable
    fun MessageCard(name: String) {

        Text(text = "hello $name!")

    }

    @Preview
    @Composable
    fun PreviewMessageCard() {//预览函数不能带参数
        
        MessageCard(name = "android")

    }

}

2.布局

在Compose中,您可以通过从可组合函数中调用其他组合函数来构建界面层次结构

使用Column 垂直排列元素,使用Row水平排列项,使用Box堆叠元素

package com.tiger.compose0117

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable

class MainActivity02 : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {

            MessageCard(Message("Android","Jetpack Compose"))

        }
    }


    @Composable
    fun MessageCard(message: Message) {

        Column {
            Text(text = message.author)
            Text(text = message.body)
        }


    }

data class Message(val author:String,val body:String)

}

?

package com.tiger.compose0117

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.painterResource

class MainActivity03 : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MessageCard(MainActivity02.Message("Android", "Jetpack Compose"))

        }
    }


    @Composable
    fun MessageCard(message: MainActivity02.Message) {

        Row {
            Image(painter = painterResource(id = R.drawable.boy),
                contentDescription = null//残障人士语音播报,这里没有,所以不需要设置,设为null
            )
            Column {
                Text(text = message.author)
                Text(text = message.body)
            }
        }


    }



}

?

3.配置布局

?

package com.tiger.compose0117

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp

class MainActivity04 : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MessageCard(MainActivity02.Message("Android", "Jetpack Compose"))

        }
    }


    @Composable
    fun MessageCard(message: MainActivity02.Message) {

        Row(modifier = Modifier.padding(all = 8.dp)) {//给整体提供一个内边距为8dp
            Image(
                painter = painterResource(id = R.drawable.boy),//引用所在res/drawable/boy.webp
                contentDescription = null,//残障人士语音播报,这里没有,所以不需要设置,设为null
                modifier = Modifier
                    .size(40.dp)//尺寸
                    .clip(CircleShape)//裁剪  CircleShape 给一个圆形的裁剪
            )
            Spacer(modifier = Modifier.width(4.dp))//设置间距  高为4个dp
            Column {
                Text(text = message.author)
                Spacer(modifier = Modifier.height(4.dp))//设置间距  高为4个dp
                Text(text = message.body)
            }
        }


    }


}

?

4.Material Design 材料设计

?

?在这个文件下设置主题与背景,

?自己添加了两行,在暗色主题下背景为灰色,在亮色主题下背景为白色

前面调用的是这个组件

?

package com.tiger.compose0117

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.tiger.compose0117.ui.theme.Compose0117Theme

class MainActivity04 : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Compose0117Theme{ //调用内部生成的 主题函数组件
                MessageCard(MainActivity02.Message("Android", "Jetpack Compose"))
            }


        }
    }


    @Composable
    fun MessageCard(message: MainActivity02.Message) {

        Row(
            modifier = Modifier.padding(all = 8.dp)//给整体提供一个内边距为8dp
                .background(MaterialTheme.colorScheme.background)//设置背景的颜色与系统的主题保持一致
        ) {
            Image(
                painter = painterResource(id = R.drawable.boy),//引用所在res/drawable/boy.webp
                contentDescription = null,//残障人士语音播报,这里没有,所以不需要设置,设为null
                modifier = Modifier
                    .size(40.dp)//尺寸
                    .clip(CircleShape)//裁剪  CircleShape 给一个圆形的裁剪
            )
            Spacer(modifier = Modifier.width(4.dp))//设置间距  高为4个dp
            Column {
                Text(text = message.author)
                Spacer(modifier = Modifier.height(4.dp))//设置间距  高为4个dp
                Text(text = message.body)
            }
        }


    }


}

代码设置好背景与 MaterialTheme 的颜色主题保持一致

效果

5. 列表和状态

5.1列表

?5.1.1 创建一个消息集合

package com.tiger.compose0117

import com.tiger.compose0117.MainActivity02.Message

//单例对象 饿汉式
object SampleData {
    val conversationSample = listOf(
        Message("jmj", "你好啊1"),
        Message("jmj", "你好啊2"),
        Message("jmj", "你好啊3"),
        Message("jmj", "你好啊4"),
        Message("jmj", "你好啊5"),
        Message("jmj", "你好啊6"),
        Message("jmj", "你好啊7"),
        Message("jmj", "你好啊8"),
        Message("jmj", "你好啊9"),
        Message("jmj", "你好啊10"),
        Message("jmj", "你好啊11"),
        Message("jmj", "你好啊12"),
        Message("jmj", "你好啊13"),
        Message("jmj", "你好啊14"),
        Message("jmj", "你好啊15"),
        )
}

5.1.2 创建数据类 Message

data class Message(val author:String,val body:String)

5.1.3 创建MessageCard组件

 @Composable
    fun MessageCard(message: Message) {

        Row(
            modifier = Modifier
                .padding(all = 8.dp)//给整体提供一个内边距为8dp
                .background(MaterialTheme.colorScheme.background)//设置背景的颜色与系统的主题保持一致
        ) {
            Image(
                painter = painterResource(id = R.drawable.boy),//引用所在res/drawable/boy.webp
                contentDescription = null,//残障人士语音播报,这里没有,所以不需要设置,设为null
                modifier = Modifier
                    .size(40.dp)//尺寸
                    .clip(CircleShape)//裁剪  CircleShape 给一个圆形的裁剪
            )
            Spacer(modifier = Modifier.width(4.dp))//设置间距  高为4个dp
            Column {
                Text(text = message.author)
                Spacer(modifier = Modifier.height(4.dp))//设置间距  高为4个dp
                Text(text = message.body)
            }
        }


    }

5.1.4 创建集合组件??Conversation

@Composable
    fun Conversation(messages: List<Message>) {
        //带缓冲的列表,存集合用的
        LazyColumn {
            //从集合里拿 集合对象
            this.items(messages) { message ->
                //取到集合里每一个元素
                //给到一个 消息组件
                MessageCard(message = message)
            }
        }
    }

5.1.5 主内容

     setContent {
            Compose0117Theme { //调用内部生成的 主题函数组件
                Conversation(SampleData.conversationSample)
            }


        }

5.1.6 效果

继续改造一下

package com.tiger.compose0117

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.tiger.compose0117.ui.theme.Compose0117Theme
import com.tiger.compose0117.MainActivity02.Message

class MainActivity05 : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Compose0117Theme { //调用内部生成的 主题函数组件
                Conversation(SampleData.conversationSample)
            }


        }
    }


    @Composable
    fun MessageCard(message: Message) {

        Row(
            modifier = Modifier
                .padding(all = 8.dp)//给整体提供一个内边距为8dp
                .background(MaterialTheme.colorScheme.background)//设置背景的颜色与系统的主题保持一致
        ) {
            Image(
                painter = painterResource(id = R.drawable.boy),//引用所在res/drawable/boy.webp
                contentDescription = null,//残障人士语音播报,这里没有,所以不需要设置,设为null
                modifier = Modifier
                    .size(40.dp)//尺寸
                    .clip(CircleShape)//裁剪  CircleShape 给一个圆形的裁剪
            )
            Spacer(modifier = Modifier.width(16.dp))//设置间距  高为4个dp

            /**
             * 这里用了委托,因为他要监控我们这个值的变化 这个值被委托的时候调用set方法会被执行 onChange
             * remember 是什么 ?  是一个私有的空间,专门存储 变量让他重新渲染的时候能拿到上一次的值
             * 它是 一个给我们 @Composable所标注的函数来存储这个变量的 ,可以动态渲染 页面
             */

            //作用域只在当前     @Composable有效
            var isExpanded by remember { //函数返回一个值
                mutableStateOf(false)
            }
            Column(modifier = Modifier.clickable { //点击事件, 调用委托
                isExpanded = !isExpanded
            }) {
                Text(
                    text = message.author,
                    color = MaterialTheme.colorScheme.secondary //主题颜色
                )
                Spacer(modifier = Modifier.height(4.dp))//设置间距  高为4个dp
                Text(
                    text = message.body,
                    modifier = Modifier.padding(all = 4.dp),
                    style = MaterialTheme.typography.bodyMedium, //给个字体
                    maxLines = if (isExpanded) Int.MAX_VALUE else 1  //默认只显示一行
                )
            }
        }


    }


    @Composable
    fun Conversation(messages: List<Message>) {
        //带缓冲的列表,存集合用的
        LazyColumn {
            //从集合里拿 集合对象
            this.items(messages) { message ->
                //取到集合里每一个元素
                //给到一个 消息组件
                MessageCard(message = message)
            }
        }
    }


}

?

实现消息的展开和闭合

6.动画

package com.tiger.compose0117

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.tiger.compose0117.ui.theme.Compose0117Theme
import com.tiger.compose0117.MainActivity02.Message

class MainActivity05 : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Compose0117Theme { //调用内部生成的 主题函数组件
                Conversation(SampleData.conversationSample)
            }


        }
    }


    @Composable
    fun MessageCard(message: Message) {

        Row(
            modifier = Modifier
                .padding(all = 8.dp)//给整体提供一个内边距为8dp
                .background(MaterialTheme.colorScheme.background)//设置背景的颜色与系统的主题保持一致
        ) {
            Image(
                painter = painterResource(id = R.drawable.boy),//引用所在res/drawable/boy.webp
                contentDescription = null,//残障人士语音播报,这里没有,所以不需要设置,设为null
                modifier = Modifier
                    .size(40.dp)//尺寸
                    .clip(CircleShape)//裁剪  CircleShape 给一个圆形的裁剪
            )
            Spacer(modifier = Modifier.width(16.dp))//设置间距  高为4个dp

            /**
             * 这里用了委托,因为他要监控我们这个值的变化 这个值被委托的时候调用set方法会被执行 onChange
             * remember 是什么 ?  是一个私有的空间,专门存储 变量让他重新渲染的时候能拿到上一次的值
             * 它是 一个给我们 @Composable所标注的函数来存储这个变量的 ,可以动态渲染 页面
             */

            //作用域只在当前     @Composable有效
            var isExpanded by remember { //函数返回一个值
                mutableStateOf(false)
            }

            val surfaceColor: Color by animateColorAsState(
                if (isExpanded) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surface
            )
            Column(modifier = Modifier.clickable { //点击事件, 调用委托
                isExpanded = !isExpanded
            }) {
                Text(
                    text = message.author,
                    color = MaterialTheme.colorScheme.secondary //主题颜色
                )
                Spacer(modifier = Modifier.height(4.dp))//设置间距  高为4个dp
             Surface(//Suface 就能使用切换主题的颜色
                 shape = MaterialTheme.shapes.medium,
                 color = surfaceColor ,
                 modifier = Modifier.animateContentSize().padding(1.dp),//动画慢慢变化,和 内边距1dp
                 shadowElevation = 1.dp //阴影
             ) {
                 Text(
                     text = message.body,
                     modifier = Modifier.padding(all = 4.dp),
                     style = MaterialTheme.typography.bodyMedium, //给个字体
                     maxLines = if (isExpanded) Int.MAX_VALUE else 1  //默认只显示一行
                 )
             }
            }
        }


    }


    @Composable
    fun Conversation(messages: List<Message>) {
        //带缓冲的列表,存集合用的
        LazyColumn {
            //从集合里拿 集合对象
            this.items(messages) { message ->
                //取到集合里每一个元素
                //给到一个 消息组件
                MessageCard(message = message)
            }
        }
    }


}

7.Compose 所解决的问题?

?

文章来源:https://blog.csdn.net/qq_53374893/article/details/135646509
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。