JetPack Compose 学习记录

官网

我的studio版本:

JetPack Compose 学习记录_第1张图片

1、开始使用

1)新建项目,使用

 

JetPack Compose 学习记录_第2张图片

2)现有项目中使用

android {
    defaultConfig {
        ...
        minSdkVersion 21
    }

    buildFeatures {
        // Enables Jetpack Compose for this module 启动jEtapck
        compose true
    }
    ...

    // Set both the Java and Kotlin compilers to target Java 8.

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = "1.8"
    }
}
//添加Jetpack Compose工具包依赖项
dependencies {
    // You also need to include the following Compose toolkit dependencies.
    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'
    ...
}

 2、基本使用

贴代码:

package com.example.compose

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.Composable
import androidx.compose.ambient
import androidx.compose.unaryPlus
import androidx.ui.core.*
import androidx.ui.foundation.DrawImage
import androidx.ui.foundation.shape.corner.RoundedCornerShape
import androidx.ui.layout.*
import androidx.ui.material.*
import androidx.ui.res.imageResource
import androidx.ui.text.style.TextOverflow
import androidx.ui.tooling.preview.Preview

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MaterialTheme {
                NewsStory("Android")
            }
        }
    }
}
@Composable
fun NewsStory(name: String) {
    val image = +imageResource(R.drawable.header)
    Column (
        crossAxisSize = LayoutSize.Expand, //橫向math
        modifier = Spacing(16.dp) //mager
    ){
        // 通过Container对图片添加样式
        Container(expanded = true, height = 180.dp ) {
            Clip(shape = RoundedCornerShape(8.dp)) {//圆角
                DrawImage(image)
            }
        }

        HeightSpacer(16.dp)     //分割线
        //文本最多顯示2行
        Text(text = "Hello $name!,你超级帅超级帅超级帅超级帅超级帅超级帅超级帅超级帅超级帅超级帅超级帅" ,
            maxLines = 2, overflow = TextOverflow.Ellipsis,style = (+themeTextStyle { h6 }).withOpacity(0.87f))
        Text(text = "Hello adsfdsaf" ,style = (+themeTextStyle { body2 }).withOpacity(0.6f))
        Text(text = "Hello 111111111111111111",style = (+themeTextStyle { body2 }).withOpacity(0.2f))
    }

}

@Preview
@Composable
fun DefaultPreview() {
    MaterialTheme {
        NewsStory("张三疯")
    }
}
 

JetPack Compose 学习记录_第3张图片

 

 

你可能感兴趣的:(JetPace,Compose,Kotlin)