我在我的应用程序列表视图中,并且当用户选择该列表视图中的一个项目时,便会创建通知。我的问题是当用户按下主页按钮并单击通知时,应用程序返回到列表视图,我需要存储最后选择的项目并再次选择它。列表视图由Fragment控制。我试图存储选择的项目项目位置saveInstanceState,但它始终为null。然后我尝试从恒定位置选择列表视图,但选择没有成功。所以我有两个问题:第一个如何在以下情况下存储所选位置用户在通知期间按下主页按钮并返回到应用程序。 第二如何以及在片段代码中选择列表视图的方式??? 这是我的尝试:
此代码在列表视图中的片段:
override fun onViewStateRestored(savedInstanceState: Bundle?) {
// here i want to get the position from the savedInstanceState but it comes null is problem number 1
// The following code doesn't works
listView.setItemChecked(2, true)
listView.setSelection(2)
listView.deferNotifyDataSetChanged()
super.onViewStateRestored(savedInstanceState)}
override fun onSaveInstanceState(outState: Bundle) {
outState.putInt(LIST_STATE,listView.selectedItemPosition)
super.onSaveInstanceState(outState)
}
这是主要活动的通知意图的代码
val notifyIntent = Intent(context, MainActivity::class.java).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
putExtras(Bundle().apply {
putParcelable(SELECTED_ITEM_FROM_NOTI, itemTracker.value)
})
}
val notifyPendingIntent = PendingIntent.getActivity(
context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT
)
这是我从主要活动中的通知中获取意图的代码
if (intent.extras != null && intent.extras!!.containsKey(SELECTED_SONG_FROM_NOTI)) {
val songWrapper = intent.extras!!.getParcelable<SongWrapper>(SELECTED_SONG_FROM_NOTI)
if (songWrapper != null) {
doNavigateDirtectToPalyer(songWrapper)
}
}
private fun doNavigateDirtectToPalyer(wrapper: Wrapper) {
val args = Bundle().apply {
putString(FILE_NAME_KEY, fileName)
putInt("Test", pos)
}
navController.navigate(R.id.Fragment2, args)
}