Kotlin-使用接口

时间:2019-03-20 09:53:38

标签: android kotlin interface

因此,我一直在kotlin上进行一些工作,其中包括带有“回收者”视图的复选框,现在我想添加一个“全部检查”按钮,但是在实现它时遇到了问题。

以下是一些代码:

MainActivity.kt(其中菜单项“全部检查”在其中):

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)

    val fragmentList: List<Fragment> = listOf(
            HomeFragment.newInstance(),
            DataFragment.newInstance()
    )

    binding.viewPager.adapter = ViewPagerAdapter(supportFragmentManager, fragmentList)
}

// Options Menu
override fun onCreateOptionsMenu(menu: Menu): Boolean {
    val inflater = menuInflater
    inflater.inflate(R.menu.main_menu, menu)
    return super.onCreateOptionsMenu(menu)
}

override fun onOptionsItemSelected(item: MenuItem?): Boolean {
    return when (item?.itemId) {
        R.id.action_selectAll -> true

        else -> super.onOptionsItemSelected(item)
    }
// Options menu end
}

interface UpdateList {
    fun updateCheckList(list: MutableList<String>)
}

}

HomeFragment.kt,我希望执行操作的片段:

class HomeFragment : Fragment(), FragmentPresenterConstructor.View, RecyclerAdapter.RecyclerAdapterClickListener, MainActivity.UpdateList {
companion object {

    fun newInstance() = HomeFragment()
}

private lateinit var pm: PackageManager
private lateinit var recyclerAdapter: RecyclerAdapter

private val presenter = FragmentPresenter(this)
private val appList = mutableListOf<AppData>()
private val checkBoxList = mutableListOf<String>()

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    recyclerAdapter = RecyclerAdapter(activity!!, appList, this)
    pm = activity!!.packageManager
}

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

    val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
    recyclerView.layoutManager = LinearLayoutManager(activity)
    recyclerView.adapter = recyclerAdapter

    return view
}

override fun onResume() {
    super.onResume()

    presenter.getData(pm)
}

override fun updateUI(data: List<AppData>) {
    appList.clear()

    appList.addAll(data)
    recyclerAdapter.notifyDataSetChanged()
}

override fun onItemClicked(isChecked: Boolean, packageName: String) {
    if (isChecked) {
        checkBoxList.add(packageName)
    } else {
        checkBoxList.remove(packageName)
    }
}

override fun updateCheckList(list: MutableList<String>) {
    checkBoxList.clear()

    checkBoxList.addAll(list)
}

}

现在,我试图在这两者之间建立一个接口,但是我不知道该如何解决?预先感谢。

1 个答案:

答案 0 :(得分:0)