Android Banner - Compose

发布时间 2023-05-23 00:00:41作者: 真菜啊

前面写了使用ViewPager和ViewPager2实现Banner的方式,今天来用Compose实现一下。
Compose相对于前两种,优势极其明显,就两个字简单!简单!还是他妈的简单
话不多说,上代码。

引入依赖

implementation("androidx.compose.foundation:foundation:1.4.3")  
implementation("androidx.compose.foundation:foundation-layout:1.4.3")

版本匹配

当前最新的compose版本匹配kotlin的1.8.10,所以需要修改下项目根目录下的build.gradle文件和模块下的build.gradle文件
根目录下的build.gradle

plugins {  
    id 'com.android.application' version '7.4.2' apply false  
    id 'com.android.library' version '7.4.2' apply false  
    id 'org.jetbrains.kotlin.android' version '1.8.10' apply false  
}

模块下的build.gradle文件

android {  
    // ...
    compileOptions {  
        sourceCompatibility JavaVersion.VERSION_1_8  
        targetCompatibility JavaVersion.VERSION_1_8  
    }  
    kotlinOptions {  
        jvmTarget = '1.8'  
    }  
    buildFeatures {  
        compose true  
    }  
    composeOptions {  
        kotlinCompilerExtensionVersion '1.4.3'  
    }  
    packagingOptions {  
        resources {  
            excludes += '/META-INF/{AL2.0,LGPL2.1}'  
        }  
    }}

代码实现

class MainActivity : ComponentActivity() {  
    override fun onCreate(savedInstanceState: Bundle?) {  
        super.onCreate(savedInstanceState)  
        setContent {  
            BannerTheme {  
                // A surface container using the 'background' color from the theme  
                Surface(  
                    modifier = Modifier.fillMaxSize(),  
                    color = MaterialTheme.colorScheme.background  
                ) {  
                    Banner(bannerItems = DataStore.getBanner())  
                }  
            }        }    }  
}  
  
@OptIn(ExperimentalFoundationApi::class)  
@Composable  
fun Banner(bannerItems: List<BannerItem>) {  
    val pagerState = rememberPagerState()  
  
    HorizontalPager(  
        pageCount = bannerItems.size,  
        state = pagerState,  
        modifier = Modifier  
            .height(180.dp)  
            .fillMaxWidth()  
            .padding(16.dp)  
    ) { index ->  
        BannerItem(bannerItems[index])  
    }  
}  
  
@Composable  
fun BannerItem(banner: BannerItem) {  
    Card(  
        modifier = Modifier  
            .fillMaxWidth()  
            .height(180.dp)  
            .clip(RoundedCornerShape(16.dp))  
            .padding(8.dp)  
    ) {  
        Image(  
            painter = painterResource(id = banner.id),  
            contentDescription = banner.desc,  
            contentScale = ContentScale.FillWidth  
        )  
    }  
}

完成,so easy!!!