库的引入
implementation "androidx.compose.runtime:runtime-livedata:1.5.0-alpha01"
implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1"
viewModel横竖屏切换使内容保持不变
@Composable
fun One() {
val viewModel: OneViewModel = viewModel(factory = OneViewModelFactory(0))
val count by viewModel.count.observeAsState(0)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(count.toString(), modifier = Modifier.padding(10.dp))
Button(
onClick = {
viewModel.onCountChanged(count + 1)
},
colors = ButtonDefaults.buttonColors(
containerColor = Color.Blue
),
) {
Text("Add Count")
}
}
}
自定义OneViewModel.kt动态数据类
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
/**
* created by cwj on 2023-12-25
* Description:
*/
class OneViewModel(defaultCount: Int) : ViewModel() {
private val _count = MutableLiveData(defaultCount)
val count: LiveData get() = _count
fun onCountChanged(count: Int) {
_count.postValue(count)
}
}
class OneViewModelFactory(private val defaultCount: Int) : ViewModelProvider.Factory {
override fun create(modelClass: Class): T {
return OneViewModel(defaultCount) as T
}
}
viewModel实现重启应用内容不清理(SharedPreferences数据保存,重启获取)
@Composable
fun Two() {
val context = LocalContext.current
val sp = context.getSharedPreferences("count_file", Context.MODE_PRIVATE)
val defaultCount = sp.getInt("DEFAULT_COUNT", 0)
val viewModel: OneViewModel = viewModel(factory = OneViewModelFactory(defaultCount))
val count by viewModel.count.observeAsState(defaultCount)
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Text(count.toString(), modifier = Modifier.padding(10.dp))
Button(
onClick = {
val counts = count + 1
viewModel.onCountChanged(counts)
sp.edit {
putInt("DEFAULT_COUNT", counts)
}
},
colors = ButtonDefaults.buttonColors(
containerColor = Color.Blue
),
) {
Text("Add Count")
}
Button(
onClick = {
sp.edit().clear().apply()
viewModel.onCountChanged(0)
},
modifier = Modifier.padding(10.dp),
colors = ButtonDefaults.buttonColors(
containerColor = Color.Blue
),
) {
Text("Clear Count")
}
}
}
库的引入
//Navigation页面跳转库
implementation "androidx.navigation:navigation-compose:2.6.0-alpha08"
//gson数据解析库
implementation 'com.google.code.gson:gson:2.8.9'
Navigation跳转页面传参
/**
* Navigation实现页面跳转
*/
@Composable
fun NavigationTest(
//开始页面
startDestination: String = "one_page"
) {
val navController = rememberNavController()
NavHost(
navController = navController,
startDestination = startDestination
) {
composable("one_page") {
OnePage(navController)
}
composable(
"two_page/{name}/{age}?hobby={hobby}/{people}",
//定义参数类型,不定义默认字符串,Int类型的会解析有问题
arguments = listOf(
navArgument("name") { type = NavType.StringType },
navArgument("age") { type = NavType.IntType },
//添加可选参数
navArgument("hobby") {
type = NavType.StringType
defaultValue = "打篮球"
},
//添加实体类参数
navArgument("people") { type = NavType.StringType },
),
) {
val defaultPeople = it.arguments?.getString("people", "") ?: ""
val people = Gson().fromJson(defaultPeople, People::class.java)
TwoPage(
navController,
it.arguments?.getString("name", "") ?: "",
it.arguments?.getInt("age") ?: 0,
it.arguments?.getString("hobby", "") ?: "",
people
)
}
}
}
/**
* 页面二
*/
@Composable
fun TwoPage(
navController: NavHostController,
name: String,
age: Int,
hobby: String,
people: People
) {
Column(
modifier = Modifier
.fillMaxSize(),
) {
Row(
modifier = Modifier
.fillMaxWidth()
.background(Color.White),
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier
.padding(5.dp)
.clickable {
//返回上个页面
navController.navigateUp()
},
painter = painterResource(id = R.drawable.back),
contentDescription = "",
)
Text(
text = "TwoPage",
modifier = Modifier
.fillMaxWidth()
.padding(5.dp),
)
}
Text(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp),
text = "${name}今年${age}岁,爱好${hobby}\n" +
"${people.name}今年${people.age}岁,爱好${people.hobby}",
textAlign = TextAlign.Center,
)
}
}
/**
* 页面一
*/
@Composable
fun OnePage(navController: NavHostController) {
val people = People("李四", 20, "打游戏")
val gson = Gson().toJson(people)
Column(
modifier = Modifier
.fillMaxSize(),
) {
Text(
text = "OnePage",
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.background(Color.White)
.padding(5.dp),
)
Button(
modifier = Modifier.padding(10.dp),
onClick = {
//跳转到TwoPage页面
navController.navigate("two_page/张三/18?hobby=打乒乓球/$gson")
},
colors = ButtonDefaults.buttonColors(
containerColor = Color.Blue
)
) {
Text(
text = "点击跳转到下个页面",
)
}
}
}
startDestination属性设置开始页面,composable中route属性设置跳转页面路由及传参,arguments给参数定义数据类型。
跳转页面用navController.navigate并添加路由及传参数据。
返回上个页面用navController.navigateUp()。
People.kt实体类
data class People(val name: String, val age: Int, val hobby: String)