Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

247
Vistas
Quiero guardar el último botón en el que se hizo clic (el estado de la vista del reciclador) en las preferencias compartidas

Estoy creando una aplicación de noticias, tengo una vista de reciclador con botones que tienen el nombre de categoría de noticias. Quiero guardar el estado de la vista del reciclador después de destruir la aplicación. Por ejemplo, si hago clic en Categorías deportivas, después de destruir la aplicación y volver a abrirla, la aplicación debería tener una categoría deportiva seleccionada. El código no tiene un error pero no guarda el estado. El código está escrito en fragmento.

Algo de mi código

 var isFilterFromCategories = false class HomeFragment : Fragment(), Callback, HomePageAdapter.Listener,CategoryListener { private lateinit var binding : FragmentHomeBinding private lateinit var adapter: HomePageAdapter private lateinit var menuAdapter: MenuAdapter private lateinit var currentCategory : String private val viewModel by activityViewModels<ArticleViewModel>() private var lastPosition : Int = 0 private var firstTime = true private fun showPopUp(view: View) { val popup = PopupMenu(context, view, Gravity.RIGHT) popup.inflate(R.menu.content_of_dropdown_menu) popup.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item: MenuItem? -> when (item!!.itemId) { R.id.dm_raportimi -> { reportArticle() } } true }) popup.show() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment binding = DataBindingUtil.inflate(inflater,R.layout.fragment_home, container, false) val window = requireActivity().window window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.statusBarColor = Color.BLACK return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val snapHelper = PagerSnapHelper() snapHelper.attachToRecyclerView(binding.recyclerView) setDrawerOpeningFunctionality() initRecyclerView() initMenuRecyclerView() viewModel.initializeList() val pref = requireActivity()!!.getPreferences(Context.MODE_PRIVATE) lastPosition = pref.getInt("lastpos",0) topMenuRecyclerView.scrollToPosition(lastPosition) topMenuRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { lastPosition = (topMenuRecyclerView.layoutManager as LinearLayoutManager?)!!.findFirstVisibleItemPosition() } }) viewModel.getArrayList().observe(requireActivity()){ adapter.setArticles(it) } } override fun onDestroy() { super.onDestroy() //save position in Shared Preferences val pref = requireActivity()!!.getPreferences(Context.MODE_PRIVATE) val e = pref.edit() e.putInt("lastpos",lastPosition) Log.d("lololo",lastPosition.toString()) e.apply() } override fun onResume() { super.onResume() if (isFilterFromCategories) { isFilterFromCategories = false setUpComingFromCategorySelection() } } private fun initRecyclerView(){ adapter = HomePageAdapter(requireContext(), this) binding.recyclerView.adapter = adapter } private fun initMenuRecyclerView(){ menuAdapter = MenuAdapter(requireContext(),this) binding.topMenuRecyclerView.apply { adapter = menuAdapter } } private fun openWebLink(url: String){ val webIntent: Intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) startActivity(webIntent) } private fun shareLink(title: String, url: String){ val sharingIntent = Intent.createChooser(Intent().apply { action = Intent.ACTION_SEND putExtra(Intent.EXTRA_TEXT, "https://developer.android.com/training/sharing/") putExtra(Intent.EXTRA_SUBJECT,url) // (Optional) Here we're setting the title of the content putExtra(Intent.EXTRA_TITLE, title) // (Optional) Here we're passing a content URI to an image to be displayed type = "rext/plain" flags = Intent.FLAG_GRANT_READ_URI_PERMISSION }, null) startActivity(sharingIntent) } override fun sourceOfInformationClicked(link: String) { openWebLink(link) } override fun shareLinkInformationClicked(name:String, link:String){ shareLink(name,link) } override fun showMoreOnClicked(view: View){ showPopUp(view) } private fun reportArticle() { val action = HomeFragmentDirections.actionHomeFragmentToReportFragment() findNavController().navigate(action) } private fun setDrawerOpeningFunctionality() { val drawerLayout = requireActivity().findViewById<DrawerLayout>(R.id.drawer_layout) drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); binding.btnNavDraw.setOnClickListener { with(drawerLayout){ if (!isDrawerOpen(GravityCompat.END)){ openDrawer(GravityCompat.END) } else { closeDrawer(GravityCompat.END) } } } } override fun changeCategory(category: String){ viewModel.setNews(category) binding.topMenuRecyclerView.adapter?.notifyDataSetChanged() } override fun selectCategoryListener(category: String, pos: Int) { TODO("Not yet implemented") } private fun setUpComingFromCategorySelection(){ val args: HomeFragmentArgs by navArgs() currentCategory = args.category menuAdapter.setCategory(currentCategory) menuAdapter.selected.add(args.position) binding.topMenuRecyclerView.scrollToPosition(args.position) viewModel.setNews(currentCategory) } }
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Debe guardar la posición en el clic del elemento. No guardar la posición en onDestroy

 private const val TAG = "DeviceAdapter" class DeviceAdapter( private val context: Context , private val list: MutableList<UsbDevice> , private val callback: (device: UsbDevice) -> Unit): RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val inflater = LayoutInflater.from(context) val binding = ItemDeviceBinding.inflate(inflater,parent,false) return MyViewHolder(binding) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val device = list[position] if (holder is MyViewHolder){ holder.binding.textHere.text = device.deviceName holder.binding.textHere.setOnClickListener { val pref = context.getSharedPreferences("SHARED_PREFERENCES_KEY", Context.MODE_PRIVATE) val editor = pref.edit() editor.putInt("lastPos",position) editor.apply() } } } override fun getItemCount(): Int { return list.size } class MyViewHolder(val binding: ItemDeviceBinding): RecyclerView.ViewHolder(binding.root)

}

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda