如何解决为什么 LinearLayout.addView(View) 在 ViewPager2 中的最后一页添加视图?
我有一个 ViewPager2,它有一个可重用的 Fragment,里面有一个 LinearLayout,LinearLayout 通过底部工具栏上的 clickListener 动态填充,有 3 个按钮,一个用于添加 EditText,第二个用于拍照并将图像添加到 ImageView ,最后一个打开图库以选择一张图片并将其添加到 ImageView。
通过这种方式,ViewPager 上的页面是动态独立填充的。
问题是,当我滑动到最新页面并返回到第一页时,新的视图会添加到最后一页,而不是用户所在的页面(或片段)中。
我认为 gif 可以更好地解释这一切:
我将 FragmentStateAdapter 用于 ViewPager 适配器:
class NoteAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
override fun getItemCount(): Int = 3
override fun createFragment(position: Int): Fragment {
return if (position == itemCount - 1){
LastPageFragment().apply { arguments = Bundle().apply { putInt(ARG_KEY,position) } }
}else {
NoteFragment().apply { arguments = Bundle().apply { putInt(ARG_KEY,position) } }
}
}
companion object {
private const val ARG_KEY = "key"
}
}
NoteFragment 是按住按钮 onClick 工具栏逻辑:
class NoteFragment : Fragment() {
private var layout: LinearLayout? = null
private lateinit var currentPhotoPath: String
private lateinit var uri: Uri
private val viewModel by activityViewModels<ViewModel>()
private var pageNumber: Int? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
pageNumber = arguments?.getInt(ARG_KEY)
}
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_note,container,false)
}
override fun onViewCreated(view: View,savedInstanceState: Bundle?) {
super.onViewCreated(view,savedInstanceState)
layout = view.findViewById(R.id.note_layout)
val navHost = parentFragment?.parentFragment as NavHostFragment
view.findViewById<TextView>(R.id.page_date_tv).apply { text = SimpleDateFormat("E,dd MMM yyyy HH:mm",Locale.getDefault()).format(Date()) }
addTextFieldOnTextButtonClick()
openGalleryOnImageButtonClickIfPermissionGranted()
openCameraOnCameraButtonClickIfPermissionGranted()
parentFragment?.view?.findViewById<ImageView>(R.id.back_cross)?.setOnClickListener { navHost.findNavController().popBackStack() }
parentFragment?.view?.findViewById<TextView>(R.id.appbar_done)?.setOnClickListener {
viewModel.isInEditMode.value = !viewModel.isInEditMode.value!!
}
}
private fun addTextFieldOnTextButtonClick() {
parentFragment?.view?.findViewById<TextView>(R.id.toolbar_add_text)?.setOnClickListener {
layout?.addView(EditText(context).apply {
hint = getString(R.string.add_a_text_hint)
background = null
updatePadding(bottom = 16F.toDP(context))
})
}
}
private fun openGalleryOnImageButtonClickIfPermissionGranted() {
val getImageFromGallery = registerForActivityResult(ActivityResultContracts.GetContent()) {
if (it == null) Toast.makeText(context,getString(R.string.not_image_selected),Toast.LENGTH_SHORT).show()
else loadImageFromUri(it)
}
val requestPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { success ->
if (success) getImageFromGallery.launch("image/*")
else Toast.makeText(context,getString(R.string.permission_denied_message),Toast.LENGTH_SHORT).show()
}
parentFragment?.view?.findViewById<TextView>(R.id.toolbar_add_image)?.setOnClickListener {
requestPermission.launch(Manifest.permission.READ_EXTERNAL_STORAGE)
}
}
private fun openCameraOnCameraButtonClickIfPermissionGranted() {
val getCameraImage = registerForActivityResult(ActivityResultContracts.TakePicture()) { success ->
if (success) loadImageFromUri(uri)
}
val requestMultiplePermission = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { resultsMap ->
resultsMap.forEach {
Toast.makeText(context,"Permission ${it.key} was granted ${it.value}",Toast.LENGTH_SHORT).show()
}
if (resultsMap.values.contains(false)) Toast.makeText(context,"One or more permission was denied",Toast.LENGTH_SHORT).show()
else {
uri = FileProvider.getUriForFile(requireContext(),"com.example.app.fileprovider",createImageFile())
getCameraImage.launch(uri)
}
}
parentFragment?.view?.findViewById<TextView>(R.id.toolbar_add_image_from_camera)?.setOnClickListener {
requestMultiplePermission.launch(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA))
}
}
private fun loadImageFromUri(data : Uri?){
layout?.addView(ImageView(context).apply {
Glide.with(requireContext()).load(data).apply(RequestOptions.centerInsideTransform()).into(this)
})
}
companion object {
private const val ARG_KEY = "key"
}
}
希望你能帮助我!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。