Ошибка надувать android .support.v7.widget.CardView - PullRequest
0 голосов
/ 22 апреля 2020

Перед погружением в код я хочу упомянуть, что Android Studio сообщает Не найден следующий класс: android .support.v7.widget.CardView , даже если он у меня загружен. (Изображения ниже)

( Ошибка, при которой CardView не найден, хотя опция загрузки не найдена.) Error saying CardView not found, though no download option is found.

Вот код действия с ошибкой.

ContactsActivity.kt

(contactView - это RecyclerView)

package com.smartherd.msgshareapp

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.smartherd.msgshareapp.models.Contact
import com.smartherd.msgshareapp.models.adapters.ContactAdapter
import kotlinx.android.synthetic.main.activity_contacts.*

class ContactsActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.VERTICAL

        contactsView.layoutManager = layoutManager  // Oops! contactsView is NULL!

        contactsView.adapter = ContactAdapter(this, Contact.allContacts)
    }
}

Вот activity_contact. xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="vertical"
    android:padding="10dp">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/contactsView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />
</LinearLayout>

Класс контакта

package com.smartherd.msgshareapp.models

import org.json.JSONArray
import org.json.JSONObject
import java.io.File

data class Contact(val name: String, val phone: String, val email: String) {
    companion object {

       val allContacts: List<Contact>
        get() {
            val json = JSONObject(File("contacts.json").readText()).getJSONArray("contacts")
            // Looks like {"contacts": [{"name": ..., "email": ..., "phone": ...}, ...]}

            val contacts = mutableListOf<Contact>()

            var i = 0

            while (i < json.length()) {
                val name = json.getJSONObject(i).getString("name")
                val phone = json.getJSONObject(i).getString("phone")
                val email = json.getJSONObject(i).getString("email")

                contacts.add(Contact(name, phone, email))

                ++i
            }

            return contacts
        }

    }
}

И класс адаптера контакта (ContactAdapter.kt)

package com.smartherd.msgshareapp.models.adapters

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.smartherd.msgshareapp.R
import com.smartherd.msgshareapp.models.Contact
import kotlinx.android.synthetic.main.card_contact.view.*

class ContactAdapter(val context: Context, val contacts: List<Contact>) :
    RecyclerView.Adapter<ContactAdapter.ContactHolder>() {

    inner class ContactHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun initialize(contact: Contact) {
            itemView.contactName.text = "${contact.name}\n${contact.email}"
            // itemView.contactImage is not set yet.
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactHolder =
        ContactHolder(
            LayoutInflater.from(context).inflate(R.layout.card_contact, parent, false)
        )

    override fun getItemCount(): Int = contacts.size

    override fun onBindViewHolder(holder: ContactHolder, position: Int) = holder.initialize(contacts[position])
}

Ответы [ 2 ]

2 голосов
/ 22 апреля 2020

При первом добавлении setContentView();

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main) //missing
    val recyclerView = findViewById(R.id.contactsView) as RecyclerView

Использовать точную версию App Level build.gradle

 dependencies {

       implementation 'com.android.support:cardview-v7:28.0.0'
       implementation 'com.android.support:recyclerview-v7:28.0.0'
      }

FYI

Вы используете очень старые версии. Если вы хотите использовать последнюю версию, библиотеки не будут работать, если вы не внесете следующие изменения в свое приложение:

  • Обновите compileSdkVersion до 28 или более поздней версии.
  • Обновите приложение, чтобы использовать Jetpack ( AndroidX).

AndroidX заменяет исходные API библиотек поддержки пакетами в пространстве имен androidx. Прочитайте официальное руководство о AndroidX Overview.

Ваш Cardview & recyclerview будет

 implementation 'androidx.cardview:cardview:1.0.0'
 implementation 'androidx.recyclerview:recyclerview:1.1.0'
1 голос
/ 23 апреля 2020

Хорошо, с помощью @IntellijAmiya в чате, я понял, что это в основном потому, что я использовал «android .support.v7.widget.CardView», когда я должен был использовать альтернативу androidX в app / build.gradle. , Кроме того, в файле XML для разработки карт я не использовал альтернативу androidX. Это исправить.

...