1.Gradle導入函示庫
implementation 'com.google.code.gson:gson:2.8.5'
implementation "org.jetbrains.anko:anko:0.10.8"
implementation 'com.github.bumptech.glide:glide:4.9.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
2.先創建JSON抓下來的JavaBean
可以去載外掛
file>Settings>Plugins>JSON To Kotlin Class>重啟Android Studio
使用
Alt + Insert
data class NewsApi(
val articles: List<Article>,
val status: String,
val totalResults: Int
)
data class Article(
val author: String,
val content: Any,
val description: String,
val publishedAt: String,
val source: Source,
val title: String,
val url: String,
val urlToImage: String
)
data class Source(
val id: Any,
val name: String
)
3.利用Gson解析JSON
val myURL = "https://newsapi.org/v2/top-headlines?country=tw&apiKey=a43a0c3447c448b795632938f18f13f6"
doAsync {
val json = URL(myURL).readText()
val newsApi = Gson().fromJson<NewsApi>(json, NewsApi::class.java)
uiThread {
recycler.adapter = ArticleAdapter(newsApi.articles)
}
}
4.配合RecyclerView 創建ViewHolder
recycler.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(this@MainActivity)
}
class ArticleHolder(view: View) : RecyclerView.ViewHolder(view) {
val image = view.article_image
val title = view.article_title
}
5.創建Adapter
inner class ArticleAdapter(val articles: List<Article>) : RecyclerView.Adapter<ArticleHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleHolder {
return ArticleHolder(layoutInflater.inflate(R.layout.row_article, parent, false))
}
override fun getItemCount(): Int {
return articles.size
}
override fun onBindViewHolder(holder: ArticleHolder, position: Int) {
val article = articles.get(position)
holder.title.text = article.title
if (article.urlToImage != null) {
Glide.with(holder.itemView.context)
.load(article.urlToImage)
.override(150, 120)
.into(holder.image)
} else {
Glide.with(holder.itemView.context)
.load("https://www.bomb01.com/upload/news/original/c95e0d21eda50ebc16d5f8ef568f60a7.png")
.override(150, 500)
.into(holder.image)
}
holder.itemView.setOnClickListener {
val intent = Intent(this@MainActivity, WebActivity::class.java)
intent.putExtra("URL", article.url)
startActivity(intent)
}
}
}