You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SharedElementTransition声明未识别:为何出现两个引用解析错误?

已配置导入与依赖,为何仍出现Unresolved reference错误?

遇到以下两个未解析引用错误:

Unresolved reference: rememberSharedElementFor
Unresolved reference: sharedElement


MainActivity.kt

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.*
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 androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.compose.ui.text.font.FontWeight


// Sample data class
data class Item(val id: String, val title: String, val imageResId: Int)

// Sample data
val items= listOf(
    Item("1", "Item 1", R.drawable.ic_launcher_foreground),
    Item("2", "Item 2", R.drawable.ic_launcher_foreground),
    Item("3", "Item 3", R.drawable.ic_launcher_foreground)
)

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            AppContent()
        }
    }
}

@Composable
fun AppContent() {
    val navController = rememberNavController()
    NavHost(navController = navController, startDestination = "list") {
        composable("list") { ItemListScreen(navController) }
        composable("details/{itemId}") { backStackEntry ->
            DetailsScreen(backStackEntry.arguments?.getString("itemId") ?: "")
        }
    }
}

// List Screen
@Composable
fun ItemListScreen(navController: NavController) {
    LazyColumn {
        items(items) { item ->
            ItemCard(item) {
                navController.navigate("details/${item.id}")
            }
        }}
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ItemCard(item: Item, onClick: () -> Unit) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp),
        onClick = onClick
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            val sharedElement = rememberSharedElementFor(item.id)
            Image(
                painter = painterResource(id = item.imageResId), // Replace with actual image resource
                contentDescription = item.title,
                modifier = Modifier
                    .size(80.dp)
                    .clip(CircleShape)
                    .sharedElement(sharedElement, "item_image_${item.id}")
            )
            Spacer(modifier = Modifier.width(16.dp))
            Text(text = item.title, style = MaterialTheme.typography.headlineSmall)
        }
    }
}

// Details Screen
@Composable
fun DetailsScreen(itemId: String) {
    val item = items.find { it.id == itemId }
    item?.let {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            val sharedElement = rememberSharedElementFor(itemId)
            Image(
                painter = painterResource(id = item.imageResId), // Replace with actual image resource
                contentDescription = item.title,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(200.dp)
                    .sharedElement(sharedElement, "item_image_${item.id}")
            )
            Spacer(modifier = Modifier.height(16.dp))
            Text(text = item.title, style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)
            // ... other details
        }
    }
}

libs.versions.toml

[versions]
agp = "8.5.0"
kotlin = "1.9.0"
coreKtx = "1.13.1"
junit = "4.13.2"
junitVersion = "1.2.1"
espressoCore = "3.6.1"
lifecycleRuntimeKtx = "2.8.2"
activityCompose = "1.9.0"
composeBom = "2024.06.00"
composeAnimation = "1.7.0-beta04"
navigationCompose = "2.7.7"

[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-animation = { group = "androidx.compose.animation", name = "animation", version.ref = "composeAnimation" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }

[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }

build.gradle.kts (Module :app)

plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.jetbrains.kotlin.android)
}

android {
    namespace = "com.plaireapps.sharedelementtransition"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.plaireapps.sharedelementtransition"
        minSdk = 30
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary = true
        }
    }

    buildTypes {
        release {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
    buildFeatures {
        compose = true
    }
    composeOptions {
        kotlinCompilerExtensionVersion = "1.5.1"
    }
    packaging {
        resources {
            excludes += "/META-INF/{AL2.0,LGPL2.1}"
        }
    }
}

dependencies {

    implementation(libs.androidx.core.ktx)
    implementation(libs.androidx.lifecycle.runtime.ktx)
    implementation(libs.androidx.activity.compose)
    implementation(platform(libs.androidx.compose.bom))
    implementation(libs.androidx.ui)
    implementation(libs.androidx.ui.graphics)
    implementation(libs.androidx.ui.tooling.preview)
    implementation(libs.androidx.material3)
    implementation(libs.androidx.navigation.compose)
    testImplementation(libs.junit)
    androidTestImplementation(libs.androidx.junit)
    androidTestImplementation(libs.androidx.espresso.core)
    androidTestImplementation(platform(libs.androidx.compose.bom))
    androidTestImplementation(libs.androidx.ui.test.junit4)
    debugImplementation(libs.androidx.ui.tooling)
    debugImplementation(libs.androidx.ui.test.manifest)

    implementation(libs.androidx.compose.animation)
    implementation(libs.androidx.navigation.compose)
}

问题原因与修复方案

核心原因

rememberSharedElementFor和sharedElement是Compose Navigation的共享元素转场API,仅在Navigation Compose 2.8.0及以上版本中提供,且属于实验性API。你的项目当前依赖的版本(2.7.7)不包含这些接口,同时Compose编译器版本与依赖版本不兼容,也会导致API无法识别。

修复步骤

1. 升级Navigation Compose版本

在libs.versions.toml中更新navigationCompose版本到2.8.0及以上(推荐使用稳定版,比如2.8.2):

navigationCompose = "2.8.2"

2. 适配Compose编译器与Kotlin版本

你的Compose BOM版本是2024.06.00(对应Compose 1.7.0),需要匹配:

  • 在libs.versions.toml中升级Kotlin版本:
    kotlin = "1.9.20"
    
  • 在build.gradle.kts中更新Compose编译器版本:
    composeOptions {
        kotlinCompilerExtensionVersion = "1.6.0"
    }
    

3. 添加必要的导入与实验性注解

在MainActivity.kt中添加以下导入:

import androidx.navigation.compose.ExperimentalSharedElementApi
import androidx.navigation.compose.rememberSharedElementFor
import androidx.compose.ui.Modifier.sharedElement

然后在使用共享元素API的Composable函数上添加实验性注解,或者直接在文件顶部添加全局注解:

@file:OptIn(ExperimentalSharedElementApi::class)

4. 同步并重建项目

点击Android Studio右上角的「Sync Now」同步依赖,然后执行「Build → Clean Project」和「Build → Rebuild Project」,确保依赖正确加载。


内容的提问来源于stack exchange,提问作者wbk727

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 13:33:11