Элементы RecyclerView смещены только при добавлении - PullRequest
0 голосов
/ 13 июля 2020

У меня есть RecyclerView, который содержит элементы, введенные в диалоговом окне, RV также является частью диалогового окна, и элементы отображаются при нажатии кнопки. Элемент представляет собой просто LinearLayout TextView, ширина которого соответствует родительскому RV, а текст текстового представления центрирован.

Проблема в том, что когда я добавляю новый элемент, они оказываются очень далеко слева. Это только тогда, когда я прокручиваю элемент из поля зрения, а затем возвращаю его к элементам, появляющимся в центре. Кроме того, если я закрою диалоговое окно и снова открою его, элементы будут отображаться с правильным выравниванием при повторном открытии. Тем не менее, если я добавлю новый элемент, он будет иметь неправильное выравнивание.

ОБНОВЛЕНИЕ: я изменил цвет фона b c Я понял, что текстовое поле слишком маленькое. Я хочу, чтобы ширина соответствовала ширине RV, текст правильно центрирован, но телевизор не заполняет ширину RV ... Вот пи c: enter image description here

See code below:

SpecAdapter.kt

    class SpecsAdapter(val context: Context, val specs: List) :
    RecyclerView.Adapter() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.item_spec, parent, false))
    }

    override fun getItemCount() = specs.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val spec = specs[position]
        holder.bind(spec)
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(spec: Specification) {
            itemView.tvSpec.text = "    ${spec.name}    "
            if (!spec.include) {
                itemView.tvSpec.apply {
                    paintFlags = Paint.STRIKE_THRU_TEXT_FLAG
                }
            }
        }
    }
}

Main Activity.kt (the part with the dialog where the RV appears)

fun showSpecificationDialog(specType: String) {
    val searchFormView = LayoutInflater.from(this).inflate(R.layout.specification_add, null)

    val dialog = AlertDialog.Builder(this)
        .setTitle("Include/Exclude")
        .setView(searchFormView)
        .setNeutralButton("Close", null)
        .show()

    dialog.findViewById(R.id.etSearch)?.hint = "Enter $specType"

    val rvSpecs = dialog.findViewById(R.id.rvSpecs)
    val adapter = if (specType == "Ingredient") SpecsAdapter(this, ingredients) else SpecsAdapter(this, tags)
    rvSpecs?.adapter = adapter
    rvSpecs?.layoutManager = LinearLayoutManager(this)

    //clicking this adds the item to one of two lists, which appears in the recyclerview
    dialog.findViewById

specification_add.xml (this holds the recyclerview and the buttons and whatnot)

<?xml version="1.0" encoding="utf-8"?>
 

item_add. xml (xml файл для каждого отдельного элемента в RV)

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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">
    <TextView
        android:id="@+id/tvSpec"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="8sp"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="24sp"
        tools:text="Ingredient/Tag" />
</LinearLayout>

1 Ответ

0 голосов
/ 13 июля 2020

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...