“主要活动”
正如您通过错误看到我的代码,lateint var is not initilizing 导致:kotlin.UninitializedPropertyAccessException:lateinit property recyclerViewAdapter has not been initialized at com.example.recyler_view_data_binding.MainActivity.onCreate(MainActivity.kt:22)
包 com.example.recyler_view_data_binding
import Dats_Sources.dats_source_class
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.recyler_view_data_binding.databinding.ActivityMainBinding
import javax.sql.DataSource
class MainActivity : AppCompatActivity() {
lateinit var mainActivitybinding : ActivityMainBinding
private lateinit var recyclerViewAdapter: Recycler_view_Adapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mainActivitybinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mainActivitybinding.root)
val dataset = dats_source_class.createDataSet()
recyclerViewAdapter.submitlist(dataset)
val recyclerview = mainActivitybinding.recyclerView
recyclerview.adapter = Recycler_view_Adapter()
recyclerview.layoutManager= LinearLayoutManager(this , LinearLayoutManager.VERTICAL , false)
}
}
“适配器类”包 com.example.recyler_view_data_binding
import Models.Blog_Post
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.ViewAnimator
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import org.w3c.dom.Text
class Recycler_view_Adapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private var item : List<Blog_Post> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val inflater : LayoutInflater = LayoutInflater.from(parent.context)
val view : View = inflater.inflate(R.layout.layout_blog_list_item , parent , false )
return viewholder(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when(holder){
is viewholder -> {
holder.bind(item.get(position))
}
}
}
override fun getItemCount(): Int {
return item.size
}
fun submitlist(blogPost: List<Blog_Post>){
item = blogPost
}
class viewholder (val itemview : View ) : RecyclerView.ViewHolder(itemview){
val blog_image = itemview.findViewById<ImageView>(R.id.blog_image)
val blog_title = itemview.findViewById<TextView>(R.id.blog_title)
val user_name = itemview.findViewById<TextView>(R.id.blog_author)
fun bind(blogPost: Blog_Post){
blog_title.setText(blogPost.title)
user_name.setText(blogPost.username)
val requestOptions = RequestOptions().placeholder(R.drawable.ic_launcher_background).error(R.drawable.ic_launcher_background)
Glide.with(itemView.context).applyDefaultRequestOptions(requestOptions)
.load(blogPost.image).into(blog_image)
}
}
}