Как правильно привязать элементы к перечню утилит в kotlin? - PullRequest
0 голосов
/ 17 марта 2020

Я занимаюсь разработкой новостного приложения и слежу за MVVM с привязкой данных в представлении переработчика. Я пытаюсь связать элементы, но я просто застрял ниже элементов в представлении переработчика xml file

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

<layout>

    <data>

        <variable
            name="article"
            type="yodgorbek.komilov.musobaqayangiliklari.model.Article">

        </variable>
    </data>

    <androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginBottom="16dp">

            <ImageView
                android:text="@{article.urlToImage}"
                android:id="@+id/imageView"
                android:layout_width="100dp"
                android:layout_height="85dp"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:contentDescription="bbc"
                tools:background="@color/colorPrimary" />

            <TextView
                android:id="@+id/articleTitle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="16dp"
                android:layout_marginEnd="16dp"

                android:layout_toEndOf="@id/imageView"
                android:layout_toRightOf="@id/imageView"
                android:ellipsize="end"
                android:lines="3"
                android:maxLines="3"
                android:text="@{article.title}" />

            <ImageView
                android:id="@+id/imageCategory"
                android:layout_width="32dp"
                android:layout_height="32dp"
                android:layout_below="@id/articleTitle"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:layout_toEndOf="@id/imageView"
                android:layout_toRightOf="@id/imageView"
                android:src="@drawable/ic_espn"
                tools:background="@color/colorPrimary" />

            <TextView
                android:id="@+id/articleSourceName"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_below="@id/articleTitle"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:layout_toEndOf="@id/imageCategory"
                android:layout_toRightOf="@id/imageCategory"
                android:gravity="center|start"
                android:text="@{article.source.name}" />

            <TextView
                android:id="@+id/articleTime"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_below="@id/articleTitle"
                android:layout_alignParentEnd="true"
                android:layout_alignParentRight="true"
                android:layout_marginStart="16dp"
                android:layout_marginEnd="16dp"
                android:layout_toEndOf="@id/articleSourceName"
                android:layout_toRightOf="@id/articleSourceName"
                android:gravity="center|start"
                android:text="@{article.publishedAt}"
                android:textColor="@android:color/darker_gray"
                tools:ignore="NotSibling" />
        </RelativeLayout>

    </androidx.cardview.widget.CardView>
</layout>

ниже TopHeadlinesAdapter .kt, где я пытаюсь реализовать логи привязки данных c

@Suppress("NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS")
class TopHeadlinesAdapter(val context: Context, private val article: List<Article>) :
    RecyclerView.Adapter<TopHeadlinesAdapter.MyViewHolder>() {


    private var articleList: List<Article> by Delegates.observable(emptyList()) { _, _, _ ->

        notifyDataSetChanged()

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {

        val inflater =
            LayoutInflater.from(parent.context)//.inflate(R.layout.news_list, parent, false)
       // val binding = Article.inflate(inflater)
        return MyViewHolder(article, parent)
    }

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

    @SuppressLint("NewApi")
    override fun onBindViewHolder(holder: MyViewHolder, position: Int) =
        holder.bind(articleList[position])

    //holder.articleTitle.text = articleList.get(position).title
    //holder.articleSourceName.text = articleList.get(position).source.name
    //Picasso.get().load(articleList.get(position).urlToImage).into(holder.image)

//    val input = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX")
//    val output = SimpleDateFormat("dd/MM/yyyy")
//    var d = Date()
//    try {
//        d = input.parse(articleList[5].publishedAt)
//    } catch (e: ParseException) {
//        try {
//            val fallback = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
//            fallback.timeZone = TimeZone.getTimeZone("UTC")
//            d = fallback.parse(articleList[5].publishedAt)
//        } catch (e2: ParseException) {
//            // TODO handle error
//            val formatted = output.format(d)
//            val timelinePoint = LocalDateTime.parse(formatted)
//            val now = LocalDateTime.now()
//
//            var elapsedTime = Duration.between(timelinePoint, now)
//
//            println(timelinePoint)
//            println(now)
//            elapsedTime.toMinutes()
//
//            holder.articleTime.text = "${elapsedTime.toMinutes()}"
//
//


    fun updateData(newList: List<Article>) {
        articleList = newList
        Log.e("articleListSize", articleList?.size.toString())

    }


   inner class MyViewHolder(private val binding: Article) : RecyclerView.ViewHolder(binding.root) {
        fun bind(article: Article) {
            binding.article = article
//        val image: ImageView = itemView!!.findViewById(R.id.imageView)
//        val articleTitle: TextView = itemView!!.findViewById(R.id.articleTitle)
//        val articleSourceName: TextView = itemView!!.findViewById(R.id.articleSourceName)
//        val imageCategory: ImageView = itemView!!.findViewById(R.id.imageCategory)
//        val articleTime: TextView = itemView!!.findViewById(R.id.articleTime)

        }
    }
}

ниже моего класса данных Article.kt

data class Article(
    val author: String,
    val content: String,
    val description: String,
    val publishedAt: String,
    val source: Source,
    val title: String,
    val url: String,
    val urlToImage: String
)

ниже фрагмента_top_headlines. xml где я размещаю реселлер

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ProgressBar
        android:id="@+id/pb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

ниже TopHeadlinesFragment.kt

class TopHeadlinesFragment : Fragment() {

    private val viewModel by viewModel<MainViewModel>()
    private lateinit var topHeadlinesAdapter: TopHeadlinesAdapter
    // private   val newsRepository: NewsRepository by inject()
    private lateinit var article:List<Article>


    //3
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(
            R.layout.fragment_top_headlines
            , container, false
        )


        val recyclerView = view.findViewById(R.id.recyclerView) as RecyclerView
        val pb = view.findViewById(R.id.pb) as ProgressBar
        topHeadlinesAdapter = TopHeadlinesAdapter(recyclerView.context, article)
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.adapter = topHeadlinesAdapter
        initViewModel()

        return view
    }

    private fun initViewModel() {
        viewModel?.sportList?.observe(this, Observer { newList ->
            topHeadlinesAdapter.updateData(newList)
        })

        viewModel?.showLoading?.observe(this, Observer { showLoading ->
            pb.visibility = if (showLoading) View.VISIBLE else View.GONE
        })

        viewModel?.showError?.observe(this, Observer { showError ->
            (showError)
        })

        viewModel?.loadNews()
    }
}

Я хочу знать, что мне нужно сделать для того, чтобы правильно связать элементы просмотра переработчика и показать правильно в моем приложении?

1 Ответ

0 голосов
/ 17 марта 2020

попробуйте это в

 class yourAdapterName(val context: Context, var listData: 
   MutableList<Article>) : 
   RecyclerView.Adapter<LanguageAdapter.ViewHolder>() {

lateinit var bindind: YourBinding


fun onRefresh(listData: MutableList<Article>) {
    this.listData = listData
    notifyDataSetChanged()
}

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): 
ViewHolder {
    bindind = YourBinding.inflate(LayoutInflater.from(parent.context), parent, false)

    return ViewHolder(bindind)
}

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

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.setData(listData[position])
}

inner class ViewHolder(private val binding: LangugaeItemBinding) : RecyclerView.ViewHolder(binding.getRoot()) {

    fun setData(model: Article) {
        with(binding) {
            artical = model
            executePendingBindings()
        }
    }

}

}

и вызовите их в onViewCreated во фрагменте

    val recyclerView = view.findViewById(R.id.recyclerView) as 
 RecyclerView
    val pb = view.findViewById(R.id.pb) as ProgressBar
    topHeadlinesAdapter = TopHeadlinesAdapter(recyclerView.context, 
   article)
    recyclerView.layoutManager = LinearLayoutManager(context)
    recyclerView.adapter = topHeadlinesAdapter
    initViewModel()
...