Как получить доступ к позиции RecyclerView

#android #android-recyclerview #position

#Android #android-recyclerview #позиция

Вопрос:

здесь полный новичок. Похоже, мне здесь не хватает чего-то очень простого, поэтому любые ресурсы для того, что это такое, или хорошее объяснение, были бы весьма признательны.

Я добавил представление Recycler с помощью PagerSnapHelper. Я провожу пальцем влево и вправо, и все работает нормально. Теперь, в текстовом представлении в моем activity_main.xml Я бы хотел, чтобы приложение показывало текущее положение адаптера.

Каков наилучший способ сделать это?

Я попробовал пару вещей, например. val pozycja adaptera = recyclerView.layoutManager.findContainingItemView() или некоторые странные случаи getAdapterPosition() , но я думаю, что они либо не подходят для данного случая, либо я просто неправильно их использую.

Взгляните на код ниже:

 class MainActivity : AppCompatActivity() {

@RequiresApi(Build.VERSION_CODES.O)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    //Adding RecyclerView
    val recyclerView = findViewById<RecyclerView>(R.id.recyclerview_id)

    recyclerView.run {
        layoutManager = LinearLayoutManager(
            this@MainActivity,
            LinearLayoutManager.HORIZONTAL,
            false)
        adapter = MyAdapter()
        // This makes mood_layout snap to grid (full screen)
        PagerSnapHelper().attachToRecyclerView(this)
    }

    //Accessing Recycler View position

    val widokPozycji = findViewById<TextView>(R.id.textView_position)
    val pozycjaAdaptera = recyclerView.layoutManager.findContainingItemView()




    //Adding AlertDialog to add comments
    btn_addNote.setOnClickListener {
        //Setting Inflater to inflate Dialog with comment_edit_text.xml layout
        val dialogLayout = LayoutInflater.from(this).inflate(R.layout.comment_edit_text, null)
        val builder = AlertDialog.Builder(this)
            .setView(dialogLayout)
            .show()

        //Adding Shared Preferences to save a comment on confirmCommentButton button

        builder.confirmCommentButton.setOnClickListener {

            //creating instance of Shared Preferences
            val pref = getSharedPreferences("commentSharedPreferences", Context.MODE_PRIVATE)
            val editor = pref.edit()

            //ACCESSING COMMENT WRITTEN BY USER in AlertDialog.Builder - val builder
            val insertedName = builder.editTextComment.text.toString()

            //Saving shared Preferences
            editor.apply {
                putString("STRING_KEY", insertedName)
                apply()
            }

            // Toast to confirm saved data
            Toast.makeText(this, "Comment Saved", Toast.LENGTH_SHORT).show()
            //close Dialog on CONFIRM button click
            builder.dismiss()
        }
        //CANCEL button that closes Dialog on click
        builder.cancelCommentButton.setOnClickListener{
            builder.dismiss()
        }
        builder.setOnDismissListener {

        }
    }
}

//HISTORY button taking user to HistoryActivity on click

fun history(view: View) {
    // New Activity to open HistoryActivity
    var historyActivity: Intent = Intent(applicationContext, HistoryActivity::class.java)
    startActivity(historyActivity)
}
}
  

Адаптер:

 class MyViewHolder(val view : View):RecyclerView.ViewHolder(view)

class MyAdapter : RecyclerView.Adapter<MyViewHolder>(){


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {

    val layoutInflater = LayoutInflater.from(parent.context)
    val moodInflater = layoutInflater.inflate(R.layout.mood_layout, parent, false)
    return MyViewHolder(moodInflater)
}

override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

    val context = holder.view.context

    val emoji = holder.view.emoji_img
    val background = holder.view.moodLayout_id
    val moodSelected = position

    when(moodSelected){
        0 -> {emoji.setImageResource(R.drawable.smiley_super_happy)
            background.setBackgroundColor(context.resources.getColor(R.color.banana_yellow))

        }

        1 -> {emoji.setImageResource(R.drawable.smiley_happy)
            background.setBackgroundColor(context.resources.getColor(R.color.light_sage))
        }

        2 -> {emoji.setImageResource(R.drawable.smiley_normal)
            background.setBackgroundColor(context.resources.getColor(R.color.cornflower_blue_65))
        }

        3 -> {emoji.setImageResource(R.drawable.smiley_disappointed)
            background.setBackgroundColor(context.resources.getColor(R.color.warm_grey))
        }

        4 -> {emoji.setImageResource(R.drawable.smiley_sad)
            background.setBackgroundColor(context.resources.getColor(R.color.faded_red))
        }
    }
}

override fun getItemCount(): Int {
    return 5
}
}
  

Ответ №1:

Хорошо, поэтому я использовал общие настройки для сохранения позиции и доступа к ней из других действий. Я помещаю их в onBindViewHolder. Код выглядит следующим образом:

 override fun onBindViewHolder(holder: MyViewHolder, position: Int) {

    val context = holder.view.context
    val sharedPref = holder.view.context.getSharedPreferences("position", MODE_PRIVATE)
    val editor = sharedPref.edit()

    editor.putInt("POSITION_KEY", position)
    editor.apply()