【发布时间】:2019-10-16 17:54:39
【问题描述】:
所以我的杂货项目需要我(拥有 3 周的 Android 知识)为包含类别按钮的页面制作一个 RecyclerView。这些按钮应该将用户带到带有相应产品列表的片段。
我学到的方法是,我需要为item创建一个xml,将recyclerView放到main.xml中,并编写一个适配器。
我通过基本的 TextView 示例做到了这一点,我可以在其中轻松地将 .text 放入适配器中。但在这种情况下,我的项目完全由一个按钮组成。而且我不知道如何在适配器中调用它,因为对于TextView使用setText()更容易。
我不知道会有多少按钮,因为他们说他们会为项目提供API,其中也应该有类别按钮名称。
这就是我所拥有的:
cat_unit.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/cat_btn"
android:background="#000000"
android:textColor="#ffffff"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
这是我的适配器:
CatAdapter.kt
package org.mp.chiproject01.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.RecyclerView
import org.mp.chiproject01.R
class CatAdapter(var catList: ArrayList<String>, var context: Context): RecyclerView.Adapter<ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
var v: View = LayoutInflater.from(context).inflate(R.layout.cat_unit, parent, false)
return ViewHolder(v)
}
override fun getItemCount( ): Int {
return catList.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// I don't know what to put in the bind
// Button will have different names, and I don't know how to
// Set the text for buttons
}
}
class ViewHolder(view: View): RecyclerView.ViewHolder(view){
var catBtn = view.findViewById<Button>(R.id.cat_btn)
}
这是带有 RecyclerView 的片段:
class FragmentCategory : Fragment() {
var catList: ArrayList<String>()
//Should I use 'String' or 'Button' here?
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
//View inflater for Fragment
var view = inflater.inflate(R.layout.cat_unit, container, false)
// Layout Manager and Adapter for RecyclerView
view.recyclerViewmeat.layoutManager = LinearLayoutManager(context)
view.recyclerViewmeat.adapter = CatAdapter(catList, this.context!!)
//I don't know how if I can add them as 'String' or 'Button'
//Can I do the setOnClickListener on the button the Button way
//or do I have to write my own onClick to handle this?
return view
}
}
谢谢!如果有任何提示/良好的编码实践,请告诉我!
【问题讨论】:
-
如果我知道了,所有按钮名称都是存储在
catList: ArrayList<String>中的那些字符串? -
FragmentCategory 应该扩大包含 RecyclerView 的布局。然后,适配器将为每个项目膨胀布局。在您的代码中,片段和适配器都在膨胀相同的布局:cat_unit.xml。
标签: android android-recyclerview android-adapter android-button