kotlin 如何将API中的数据提取设置为新Activity

ktecyv1j  于 2023-05-18  发布在  Kotlin
关注(0)|答案(1)|浏览(93)

我有一个新闻应用程序,我使用Retrofit从API获取数据。我用cardView和Recycler View显示了新闻。现在我想实现下一步,如果用户点击卡片,整个新闻应该显示在一个新的Activity上。但要实现这一点,我没有正确的想法,如何做到这一点。这里我提供了我的MainActivity、适配器类和用于改造的接口。我正在寻求帮助,以实施下一步。
MainActivity.kt

class MainActivity : AppCompatActivity() {
    lateinit var adapter: NewsAdapter
   
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getNews()
    }

    private fun getNews() {
        val news :Call<News> = NewsSeversis.newsIntence.getHeadlines("in",1)
        
        news.enqueue(object :Callback<News>{
            override fun onResponse(call: Call<News>, response: Response<News>) {
                //here response is a News response
                val news:News?=response.body()
                if (news!=null){
                    Log.d("response",news.toString())
                    adapter= NewsAdapter(news.articles)
                    newsList.adapter=adapter
                    newsList.layoutManager=LinearLayoutManager(this@MainActivity) 
                }
            }
            override fun onFailure(call: Call<News>, t: Throwable) {
                Log.d("response","error occur",t)
            }
        })
    } 
}

回收器视图的适配器类

class NewsAdapter (val artical: List<Artical>):RecyclerView.Adapter<NewsAdapter.articalViewHolder>(){
   inner class articalViewHolder(itemView: View):RecyclerView.ViewHolder(itemView)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): articalViewHolder {
        val view:View=LayoutInflater.from(parent.context).inflate(R.layout.item_layout,parent,false)
        return articalViewHolder(view)
    }

    override fun onBindViewHolder(holder: articalViewHolder, position: Int) {
        val articals:Artical=artical[position]
        holder.itemView.apply {
            newsTitle.text=articals.title
            newsDescription.text=articals.description
            Glide.with(context).load(articals.urlToImage).into(newsImage)

        }
    }

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

接口类

const val BASE_URL="https://newsapi.org/"
const val API_KEY="b461fea21cc242458825d1be951ebe1c"
 interface NewsInterface{
    
  @GET("v2/top-headlines?apiKey=$API_KEY")//@GET is to tell the it is a get request
    
  fun getHeadlines(@Query("country")country:String, @Query("page") page:Int) : Call<News> 
  
 }
object NewsSeversis {
   
    val newsIntence:NewsInterface
    init {
        val retrofit=Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
       
        newsIntence=retrofit.create(NewsInterface::class.java)
    }

}

每个卡片视图的布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="wrap_content"
    android:layout_margin="16dp"
    app:cardUseCompatPadding="true"
    app:cardCornerRadius="8dp"
    app:cardElevation="4dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#F1F1F1"
        android:padding="16dp">

        <ImageView
            android:id="@+id/newsImage"
            android:layout_width="match_parent"
            android:layout_height="180dp"
            android:scaleType="centerCrop"
            android:src="@drawable/ic_launcher_background"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/newsTitle"
            style="@style/TextAppearance.AppCompat.Headline"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:maxLines="2"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            android:layout_marginTop="8dp"
            android:text="Title"
            app:layout_constraintTop_toBottomOf="@+id/newsImage" />

        <TextView
            android:id="@+id/newsDescription"
            style="@style/TextAppearance.AppCompat.Body1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:maxLines="2"
            android:text="Description"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/newsTitle" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

主要活动布局

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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="match_parent"
    tools:context=".MainActivity">

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

沿着这些我有一个艺术和新闻类与构造器和一个全新的活动显示整个新闻上的活动
新闻类

ata class News(
    val totalResults:Int,
    val articles:List<Artical>
    )

艺术课

data class Artical(
    val author:String,
    val title:String,
    val description:String,
    val url:String,
    val urlToImage:String)
xytpbqjk

xytpbqjk1#

以下是从适配器中获取对项目单击活动的回调的步骤。
NewsAdapter类中,使用HigherOrder Function来获得项目单击的回调。

1.首次更新NewsAdapter

class NewsAdapter (
val artical: List<Artical>,
private val onItemClicked: () -> Unit
                ):RecyclerView.Adapter<NewsAdapter.articalViewHolder>(){
                    // your existing code 
             override fun onBindViewHolder(holder: articalViewHolder, position: Int) {
                    val articals:Artical=artical[position]
                    holder.itemView.apply {
                        newsTitle.text=articals.title
                        newsDescription.text=articals.description
                        Glide.with(context).load(articals.urlToImage).into(newsImage)
    // ADD THIS LINE 
        setOnClickListener { onItemClicked.invoke() } 
            
                    }
                }

2.现在更新MainActivity中创建NewsAdapter对象的代码。

// EXISTING CODE
adapter= NewsAdapter(news.articles){
    // CODE TO LAUNCH THE NEW ACTIVITY       
    }
// EXISTING CODE

如果有任何疑问,请随时询问。

相关问题