Проблемы с привязкой данных к RecyclerView с адаптером. Не видя модельный класс - PullRequest
1 голос
/ 14 апреля 2020

По сути, я хочу привязать данные к своему RecyclerView с помощью адаптера, но мне кажется, что я не вижу своего списка данных в Activity, где я определяю адаптер

listItems.adapter = FormRecyclerAdapter(this, TestFileManager.testForms) // testForms highlighted(unresloved reference)

Кажется, что он должен работать, но, вероятно, там Это недоразумение или другая проблема, которую я не могу решить.

Вот мои занятия

MainActivity.kt

class MainActivity: AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(activity_main)
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.title = "Forms creator"


        listItems.layoutManager = LinearLayoutManager(this)
        listItems.adapter = FormRecyclerAdapter(this, TestFileManager.testForms) <- here is where the problem occurs
    }

}

TestFileManager.kt

class TestFileManager {

    private val testForms = ArrayList<TestForm>()

    init {
        initializeForms()
    }

    fun initializeForms() {
        var testForm = TestForm("Form 1", "Created Jun 1 2020")
        testForms.set(0, testForm)

        testForm = TestForm("Form 2", "Created 5 Jan 2019")
        testForms.set(1, testForm)

        testForm = TestForm("Form 3", "Created 3 March 2020")
        testForms.set(2, testForm)
    }
}

TestForm.kt

class TestForm( var name: String, var description: String)

FormRecyclerAdapter.kt

class FormRecyclerAdapter(private val context: Context, private val forms: List<TestForm>) :
    RecyclerView.Adapter<FormRecyclerAdapter.ViewHolder>() {

    private val layoutInflater = LayoutInflater.from(context)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val itemView = layoutInflater.inflate(R.layout.item_form_list, parent, false)
        return ViewHolder(itemView)
    }

    override fun getItemCount() = forms.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val form = forms[position]
        holder.textTitle?.text = form.name
        holder.textDescription?.text = form.description
    }

    class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView!!) {
        val textTitle = itemView?.findViewById<TextView?>(R.id.textTitle)
        val textDescription = itemView?.findViewById<TextView?>(R.id.textDescription)
    }
}

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

Ответы [ 4 ]

1 голос
/ 14 апреля 2020

Попробуйте это:

fun initializeForms() {
    var testForm = TestForm("Form 1", "Created Jun 1 2020")
    testForms.add(testForm)

    testForm = TestForm("Form 2", "Created 5 Jan 2019")
    testForms.add(testForm)

    testForm = TestForm("Form 3", "Created 3 March 2020")
    testForms.add(testForm)
}

ArrayList.set (int index, E element) заменяет элемент в указанной позиции в этом списке на указанный элемент.

Ваш список пуст .

Вызов: TestFileManager (). TestForms

0 голосов
/ 14 апреля 2020

Итак, мой основной теперь выглядит следующим образом:

class MainActivity: AppCompatActivity() {

    lateinit var formRecyclerAdapter: FormRecyclerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(activity_main)
        val toolbar: Toolbar = findViewById(R.id.toolbar)
        setSupportActionBar(toolbar)
        supportActionBar?.title = "Forms creator"

        listItems.layoutManager = LinearLayoutManager(this)
        formRecyclerAdapter = FormRecyclerAdapter(this, TestFileManager.testForms)
        listItems.adapter = formRecyclerAdapter
    }

}

Проблема не решена, хотя: / Все еще не решена ссылка на .testForms Я не вижу ничего, кроме как привить этот класс. не знаю почему

0 голосов
/ 14 апреля 2020

Прежде всего, вы не инициализировали класс, сделайте это:

listItems.adapter = FormRecyclerAdapter(this, TestFileManager().testForms)

Во-вторых, вы используете неправильный оператор для добавления элементов в ArrayList, используйте add (). set () не будет добавлять элементы в ArrayList.

fun initializeForms() {
    var testForm = TestForm("Form 1", "Created Jun 1 2020")
    testForms.add(testForm)

    testForm = TestForm("Form 2", "Created 5 Jan 2019")
    testForms.add(testForm)

    testForm = TestForm("Form 3", "Created 3 March 2020")
    testForms.add(testForm)
}
0 голосов
/ 14 апреля 2020

не инициализировать

listItems.adapter = FormRecyclerAdapter(this, TestFileManager.testForms)

использовать:

создать переменную класса для адаптера

lateinit var formRecyclerAdapter: FormRecyclerAdapter

после этого в onCreate ( ) do

formRecyclerAdapter = FormRecyclerAdapter(this, TestFileManager.testForms)

после этого инициализируйте свой адаптер для представления вашего переработчика

listItems.adapter = formRecyclerAdapter
...