从Kotlin的onBindViewHolder检索变量

时间:2018-10-24 17:12:41

标签: android kotlin

我正在尝试在主类中检索变量值,因此可以将该值加载到数据库中。我不确定如何在MainClas中检索onBindViewHolder值。我可以在活动中显示该项目。

用户要求的完整代码。

    class TestProjectMenuDetail() : AppCompatActivity() { 
            var itemName=""
            override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
                setContentView(R.layout.activity_main)
                recyclerView_main.setBackgroundColor(Color.WHITE)
                recyclerView_main.layoutManager= LinearLayoutManager(this)

                   supportActionBar?.title=navBarTitle
                fetchJSON()
            }

            //Retrieve value from OnBindViewHolder
            fun setVariable(ItemName:String)
            {
                itemName=ItemName

            }
        }
        private class MenuDetailListAdapter(val TestProjectMenudetails:Array<TestProjectMenuDetails>,context: Context): RecyclerView.Adapter<TestProjectDetailMenuViewHolder>()
        {
 private  val TestVar:TestMenuDetail= context as TestMenuDetail
            override fun onBindViewHolder(p0: TestProjectDetailMenuViewHolder, p1: Int) {
                val TestProjectmenudetail=TestProjectMenudetails.get(p1)
                p0?.customView?.itemname.text=TestProjectmenudetail.menu



     TestVar.setVariable(TestProjectmenudetail.menu)

            }

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

            override fun onCreateViewHolder(p0: ViewGroup, p1: Int): TestProjectDetailMenuViewHolder {
                val layoutInflater= LayoutInflater.from(p0?.context)
                val customView=layoutInflater.inflate(R.layout.activity_TestProject_menu_detail,p0,false)
                return TestProjectDetailMenuViewHolder(customView)
            }

        }
         @Suppress("DEPRECATION")
         class TestProjectDetailMenuViewHolder(val customView: View, var Menus:TestProjectMenu?=null): RecyclerView.ViewHolder(customView)
        {
            companion object {
                val DISHES_TITLE_NAME="ITEM_NAME"
                val intialcount:Int=0
            }

            init {
                customView.setOnClickListener {
                }
            }
            fun AddClick()
            {
                val intent=Intent(customView.context,TestProjectMenuList::class.java)
                customView.context.startActivity(intent)
            }
        }

1 个答案:

答案 0 :(得分:0)

MainClas中声明一个变量,以保存要从onBindViewHolder传递的值,例如activityVar,然后创建一个方法:

fun setVariable(myVariable: Int) {
    activityVar = myVariable
}

用正确的数据类型替换Int

像这样更改适配器类的标头:

private class TestDetailListAdapter(context: Context, val ItemTestdetails:Array<ItemTestDetails>)

所以您需要先通过传递this来传递活动的上下文信息
onBindViewHolder内添加以下内容:

val mainclas: MainClas = context as MainClas 
mainclas.setVariable(variablename)

variablename替换为您要传递的变量的名称