在加载/替换回收视图片段时,如何在活动中的工具栏上添加按钮?每次加载回收视图片段时,我都试图在工具栏上添加按钮。
这是我使用的片段。
我应该提供任何类型的上下文吗?我该如何实施呢?请帮忙。谢谢。
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.samzhou.helloworld.dummy.DummyContent
import com.example.samzhou.helloworld.dummy.DummyContent.DummyItem
import com.google.gson.Gson
import kotlinx.android.synthetic.main.fragment.view.*
/**
* A fragment representing a list of Items.
* Activities containing this fragment MUST implement the
* [movieListRecycleViewFragment.OnListFragmentInteractionListener] interface.
*/
class movieListRecycleViewFragment : Fragment() {
// TODO: Customize parameters
private var columnCount = 1
val movies = """
""".trimIndent()
val roster : List<Movie> = Gson().fromJson(movies, Array<Movie>::class.java).asList()
private var listener: OnListFragmentInteractionListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
columnCount = it.getInt(ARG_COLUMN_COUNT)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_movielistrecycleview_list, container, false)
// Set the adapter
if (view is RecyclerView) {
with(view) {
layoutManager = when {
columnCount <= 1 -> LinearLayoutManager(context)
else -> GridLayoutManager(context, columnCount)
}
adapter = MymovieListRecycleViewRecyclerViewAdapter(roster, listener)
}
}
return view
}
override fun onDetach() {
super.onDetach()
listener = null
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
*
*
* See the Android Training lesson
* [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html)
* for more information.
*/
interface OnListFragmentInteractionListener {
// TODO: Update argument type and name
fun onListFragmentInteraction(item: Movie?)
}
companion object {
// TODO: Customize parameter argument names
const val ARG_COLUMN_COUNT = "column-count"
// TODO: Customize parameter initialization
@JvmStatic
fun newInstance(columnCount: Int) =
movieListRecycleViewFragment().apply {
arguments = Bundle().apply {
putInt(ARG_COLUMN_COUNT, columnCount)
}
}
}
}