Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

253
Visualizações
I want to save the last clicked button (the state of recycler view) in shared preferences

I am creating a news app, I have a recycler view with buttons that have the name of category of news. I want to save the state of recycler view after I destroyed the app. Example if I click in Sport Categories, after I destroy the app and reopen it, the app should have sport category selected. The code its not having a bug but it doesn't save the state. The code it's written in fragment

Some of my code


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 Respostas
Responde à pergunta

0

You should save position on item click.Dont save position on 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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda