0

При генерации карточек с пользователями они выглядят так (на данный момент я специально так оставил, для наглядности) (проблема сохраняется и на реальных девайсах) старт Но после первого же скролла вниз все карточки раздвигаются. после скролла И так происходит каждый раз, когда перехожу на данное активити. Как убрать "прыгание"?

class ListUserActivity : AppCompatActivity() {
    private lateinit var recycleView: RecyclerView

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

        recycleView = findViewById(R.id.user_recycle_view)
        val columns = calculateNoOfColumns(this)
        recycleView.let {
            it.setHasFixedSize(true)
            it.layoutManager = GridLayoutManager(this, columns)
            it.adapter = UserAdapter(UserFactory.createList(30))
            it.itemAnimator = DefaultItemAnimator()
            it.addItemDecoration(UserAdapter.SpacesItemDecoration(20))
        }
    }
}

fun calculateNoOfColumns(context: Context): Int {
    val displayMetrics = context.resources.displayMetrics
    val dpWidth = displayMetrics.widthPixels / displayMetrics.density
    return (dpWidth / 350).toInt()
}

Адаптер

class UserAdapter (private var users: ArrayList<User>) : RecyclerView.Adapter<UserAdapter.UserViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UserViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.user_card_view, parent, false)
        return UserViewHolder(v)
    }

    override fun getItemCount(): Int {
        return users.size
    }

    override fun onBindViewHolder(holder: UserViewHolder?, position: Int) {
        holder?.let {
            it.bind(users[position])
            it.delete.setOnClickListener(View.OnClickListener {
                users.removeAt(position)
                notifyItemRangeRemoved(position, 1)
                notifyItemRangeChanged(position, itemCount)
        })
        }
    }

    class UserViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var userId = itemView.findViewById<TextView>(R.id.user_card_id)
        var userFio = itemView.findViewById<TextView>(R.id.user_card_fio)
        val edit = itemView.findViewById<Button>(R.id.user_card_replace_button)
        val delete = itemView.findViewById<Button>(R.id.user_card_delete_button)
        lateinit var user: User

        fun bind(user: User) {
            this.user = user
            userFio.text = user.firstName + " " + user.lastName
            userId.text = "id = ${user.id}"
        }
    }

    class SpacesItemDecoration(private val space: Int) : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
            outRect?.apply {
                bottom = space
                top = space
            }
        }
    }
}

XML-код RecyclerView

<android.support.v7.widget.RecyclerView
    android:id="@+id/user_recycle_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:splitMotionEvents="false"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

</android.support.v7.widget.RecyclerView>

XML карточки

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView 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:id="@+id/user_card_view"
    android:layout_width="320dp"
    android:layout_height="120dp"
    android:fadingEdge="none">


    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/user_card_avatar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="16dp"
            android:layout_marginStart="4dp"
            android:layout_marginTop="16dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:srcCompat="@mipmap/ic_launcher_round" />

        <TextView
            android:id="@+id/user_card_fio"
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_marginStart="56dp"
            android:layout_marginTop="8dp"
            android:text="Иванов Иван Иванович"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            android:textSize="14sp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintStart_toEndOf="@+id/user_card_avatar"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/user_card_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="20dp"
            android:layout_marginTop="8dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"
            android:textSize="12sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/user_card_fio"
            tools:text="id=1202323283" />

        <Button
            android:id="@+id/user_card_replace_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="32dp"
            android:layout_marginStart="32dp"
            android:onClick="onClickEditUser"
            android:text="@string/edit"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toStartOf="@+id/user_card_delete_button"
            app:layout_constraintHorizontal_bias="0.29"
            app:layout_constraintStart_toEndOf="@+id/user_card_avatar" />

        <Button
            android:id="@+id/user_card_delete_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="4dp"
            android:text="@string/delete"
            android:textSize="12sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintRight_toRightOf="parent" />
    </android.support.constraint.ConstraintLayout>

</android.support.v7.widget.CardView>

1 ответ 1

0

1) Замените в XML карточки:

android:layout_width="320dp"
android:layout_height="120dp"

на:

android:layout_width="match_parent"
android:layout_height="120dp"

2) в функции calculateNoOfColumns захардкодьте временно значение 2. Вы там используете значение 350, а в xml 320dp, судя по всему вы хотели добавить горизонтальные отступы между ячеек в 30dp.

3) Убедитесь что 350 не нужно перевести в dp.

4) Если вам нужны горизонтальные отступы - добавьте эту логику в SpacesItemDecoration

1
  • Действительно, оказалось что нужно было сделать в карточке максимальную ширину. Спасибо!
    – indrih17
    11 ноя 2017 в 18:15

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.