Я новичок в Android и Kotlin и пытаюсь создать свое первое приложение.
По сути, я создал RecyclerView, который содержит карты.
Внутри onBindViewHolder, я добавил onClickListener, который обнаруживает нажатие на CardView и расширяет его, изменяя видимость внутренней карты ListView на «VISIBLE» или наоборот, и onClickListener, который удаляет карту.
Проблема в том, что когда карта нажимается или удаляется, другие карты также расширяются \ сворачиваются.
Я прочитал тонны потоков, но все еще не смог найти решение.
То, что я пробовал :
Установка setItemViewCacheSize на размер списка адаптера - помогает только тогда, когда карты нажимаются, а не удаляются.
Установка setHasStableIds на True и ovrriding getItemId.
Создание переменной внутри класса ViewHolder, которая поддерживает состояние ("GONE" \ VISIBLE ")
Создание списка с такого же размера, как мой ccountsList с правильным состоянием просмотра ("GONE" \ VISIBLE ") в той же позиции.
Перемещение onClickListeners в onCreateViewHolder или в сам ViewHolder
Вот мой код:
MainActivity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.account_card.*
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private var adapter : AccountAdapter? = null
private var accountsList : MutableList<Account>? = null
private var layoutManager : RecyclerView.LayoutManager? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
layoutManager = LinearLayoutManager(this)
accountsList = mutableListOf()
adapter = AccountAdapter(accountsList!!, this)
val usernameField : Field = Field("UserName", "abcd", false)
val passwordField : Field = Field("Password", "1234", false)
val extraField : Field = Field("Mail", "aaa@gmail.com", false)
val facebookAccount = Account("Facebook", 1)
facebookAccount.addField(usernameField)
facebookAccount.addField(passwordField)
facebookAccount.addField(extraField)
val gmailAccount = Account("Gmail", 2)
gmailAccount.addField(usernameField)
gmailAccount.addField(passwordField)
gmailAccount.addField(extraField)
val bankAccount = Account("Bank", 3)
bankAccount.addField(usernameField)
bankAccount.addField(passwordField)
val twitterAccount = Account("Twitter", 4)
val spotifyAccount = Account("Spotify", 5)
spotifyAccount.addField(usernameField)
spotifyAccount.addField(passwordField)
spotifyAccount.addField(extraField)
val appleAccount = Account("Apple", 6)
appleAccount.addField(usernameField)
appleAccount.addField(passwordField)
appleAccount.addField(extraField)
val samsungAccount = Account("Samsung", 7)
samsungAccount.addField(usernameField)
samsungAccount.addField(passwordField)
samsungAccount.addField(extraField)
val microsoftAccount = Account("Microsoft", 8)
microsoftAccount.addField(usernameField)
microsoftAccount.addField(passwordField)
microsoftAccount.addField(extraField)
accountsList!!.add(facebookAccount)
accountsList!!.add(gmailAccount)
accountsList!!.add(twitterAccount)
accountsList!!.add(appleAccount)
accountsList!!.add(spotifyAccount)
accountsList!!.add(samsungAccount)
accountsList!!.add(bankAccount)
accountsList!!.add(microsoftAccount)
accountsList!!.add(facebookAccount)
accountsList!!.add(gmailAccount)
accountsList!!.add(twitterAccount)
accountsList!!.add(appleAccount)
accountsList!!.add(spotifyAccount)
accountsList!!.add(samsungAccount)
accountsList!!.add(bankAccount)
accountsList!!.add(microsoftAccount)
accountsList!!.add(facebookAccount)
accountsList!!.add(gmailAccount)
accountsList!!.add(twitterAccount)
accountsList!!.add(appleAccount)
recyclerView.layoutManager = layoutManager
recyclerView.adapter = adapter
adapter!!.notifyDataSetChanged()
}
}
account_card. xml
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="20dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
app:cardCornerRadius="10dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/accountBackground"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentTop="true">
</androidx.constraintlayout.widget.ConstraintLayout>
<TextView
android:id="@+id/accountName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/accountBackground"
android:padding="10dp"
android:text="@string/account_name"
android:textSize="18sp"
android:textStyle="bold" />
<LinearLayout
android:id="@+id/buttonsBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_below="@id/accountName"
android:orientation="horizontal"
android:visibility="gone">
<ImageButton
android:id="@+id/deleteButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@color/design_default_color_background"
android:padding="10dp"
android:layout_gravity="center"
app:srcCompat="@android:drawable/ic_menu_delete"
android:contentDescription="@string/delete_button"/>
<ImageButton
android:id="@+id/editButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:background="@color/design_default_color_background"
android:padding="10dp"
app:srcCompat="@android:drawable/ic_menu_edit"
android:contentDescription="@string/edit_button"/>
<ImageButton
android:id="@+id/exposeButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:background="@color/design_default_color_background"
android:padding="10dp"
app:srcCompat="@android:drawable/ic_menu_view"
android:contentDescription="@string/expose_button"/>
</LinearLayout>
<ListView
android:id="@+id/fieldsList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/buttonsBar"
android:visibility="gone" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
AccountAdapter
import android.content.Context
import android.graphics.drawable.Drawable
import android.text.Layout
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.graphics.scaleMatrix
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.account_card.view.*
import kotlin.random.Random
class AccountAdapter(private val accountsList:MutableList<Account>,
private val context: Context) : RecyclerView.Adapter<AccountAdapter.ViewHolder>() {
var accountsImages: MutableList<Int> = mutableListOf(
R.drawable.account_image_1, R.drawable.account_image_2, R.drawable.account_image_3,
R.drawable.account_image_4, R.drawable.account_image_5, R.drawable.account_image_6)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val accountCardView : View =
LayoutInflater.from(context).inflate(R.layout.account_card, parent, false)
return ViewHolder(accountCardView)
}
override fun getItemCount(): Int {
return accountsList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindToAccount(accountsList[position], context, context.resources.getDrawable
(accountsImages[(position + accountsList[position].accountName.length) % (accountsImages.size)]))
holder.card.setOnClickListener{
if(holder.card.fieldsList.visibility==View.GONE){
holder.fieldsList.visibility=View.VISIBLE
holder.buttonsBar.visibility=View.VISIBLE
}
else{
holder.fieldsList.visibility=View.GONE
holder.buttonsBar.visibility=View.GONE
}
}
holder.deleteButton.setOnClickListener{
removeAccount(holder.adapterPosition)
}
}
fun removeAccount(position : Int){
accountsList.removeAt(position)
notifyItemRemoved(position)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var card = itemView
var accountName = itemView.findViewById(R.id.accountName) as TextView
var accountBackground = itemView.findViewById(R.id.accountBackground) as ConstraintLayout
var fieldsList = itemView.findViewById(R.id.fieldsList) as ListView
var buttonsBar = itemView.findViewById(R.id.buttonsBar) as LinearLayout
var deleteButton = itemView.findViewById(R.id.deleteButton) as ImageButton
var editButton = itemView.findViewById(R.id.editButton) as ImageButton
var exposeButton = itemView.findViewById(R.id.exposeButton) as ImageButton
fun bindToAccount(account:Account, context : Context, image : Drawable){
accountName.text = account.accountName
accountBackground.background = image
fieldsList.adapter = FieldAdapter(account.fieldsList, context)
var layoutParamsList = fieldsList.layoutParams
val scale: Float = context.resources.displayMetrics.density
layoutParamsList.height = (70 * scale * account.fieldsList.size).toInt()
}
}
}
Спасибо!