我的想法是在那里渲染个人资料图片并允许用户更改它。
为了保存所选图片,我正在使用SharedPreferences
(将 Uri 保存为字符串)。问题是每次启动时图像都不会显示。
共享管理器检索到的值似乎是正确的,但是SubComposeAsyncImageContent
无法正确显示图片。
个人资料图片可组合:
@Composable
fun ProfilePicture(
imageUri: String?,
size: Dp = 50.dp,
onClick: (String) -> Unit,
) {
val launcher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.GetContent()) { uri: Uri? ->
onClick(uri.toString())
}
if (imageUri != null) {
Log.e("ProfilePicture", imageUri)
}
SubcomposeAsyncImage(
model = imageUri,
contentDescription = "",
modifier = Modifier.clickable { launcher.launch("image/*") }
) {
val state = painter.state
Log.e("ProfilePicState", "${state}")
if (state is AsyncImagePainter.State.Loading || state is AsyncImagePainter.State.Error) {
CircularProgressIndicator()
} else {
SubcomposeAsyncImageContent()
}
}
}
我们的想法是imageUri
从配置文件屏幕(包含一个ProfilePicture
)。配置文件屏幕从以下位置获取该值viewModel
,它可以访问sharedPreferences。
ProfileScreen.kt
:
@Composable
fun ProfileScreen(viewModel: ProfileViewModel) {
var profileUri by rememberSaveable {
mutableStateOf(viewModel.getProfilePicURI())
}
Log.w("ProfileScreen", profileUri)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
ProfilePicture(
imageUri = profileUri,
size = 150.dp,
onClick = {
viewModel.onEvent(ProfileEvents.OnUpdateProfilePic(it))
profileUri = viewModel.getProfilePicURI()
}
)
}
}
最后,viewModel
:
class ProfileViewModel(val preferenceManager: PreferenceManager): ViewModel() {
fun getProfilePicURI(): String {
return preferenceManager.getProfilePic()
}
fun onEvent(event: ProfileEvents) {
when (event) {
is ProfileEvents.OnUpdateProfilePic -> {
// update the sharedpreference
preferenceManager.setProfilePic(event.newUri)
Log.e("ProfileVM", "uri stored: ${getProfilePicURI()}")
}
}
}
}
如前所述,代码在应用程序内运行,即我可以更改个人资料图片,即使我返回个人资料屏幕,它也会被记住,但每次启动时,画家都无法加载图像,即使正确的资源似乎是发送。
日志如下所示:
2022-04-27 09:29:45.174 12502-12502/com.example.insurance W/ProfileScreen: content://com.android.providers.media.documents/document/image%3A96
2022-04-27 09:29:45.182 12502-12502/com.example.insurance E/ProfilePicture: content://com.android.providers.media.documents/document/image%3A96
2022-04-27 09:29:45.258 12502-12502/com.example.insurance E/ProfilePicState: Loading(painter=null)
2022-04-27 09:29:45.274 12502-12502/com.example.insurance E/ProfilePicState: Loading(painter=null)
2022-04-27 09:29:45.278 12502-12502/com.example.insurance E/ProfilePicState: Error(painter=null, result=coil.request.ErrorResult@bfc77785)
使用后退按钮退出应用程序是可行的,在游戏中,个人资料图片就在那里。通过任务任务管理器销毁它会触发错误的行为。
当我启动应用程序时,显示个人资料图片的唯一方法是选择不同的图像,即,如果我选择之前选择的图像,则不会显示。一旦我选择一个新的,它就会再次显示