1
我在Kotlin編寫我的第一個Android應用程序,我試圖在android studio 3.0中使用kotlin在RecyclerView中實現onItemClickListner,但是我找不到任何有用的東西。所以我有movieListFRagment:Implementing onItemClickLitsner recyclerView Kotlin -android
class MoviesListFragment : Fragment() {
private var mListener: OnFragmentInteractionListener? = null
private var movieList = ArrayList<Movies>()
private var mAdapter: MoviesRecyclerAdapter? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater!!.inflate(R.layout.fragment_movies_list, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mAdapter = MoviesRecyclerAdapter(movieList)
val mLayoutManager = LinearLayoutManager(this.activity)
recyclerView!!.layoutManager = mLayoutManager
recyclerView!!.itemAnimator = DefaultItemAnimator()
recyclerView!!.adapter = mAdapter
prepareMoviesData() }
interface OnFragmentInteractionListener {
// TODO: Update argument type and name
fun onFragmentInteraction(uri: Uri)
}
private fun prepareMoviesData() {
var movie = Movies("Mad Max: Fury Road", "Action & Adventure", "2015")
movieList.add(movie)
movie = Movies("Inside Out", "Animation, Kids & Family", "2015")
movieList.add(movie)
movie = Movies("Star Wars:The Force Awakens", "Action", "2015")
movieList.add(movie)
mAdapter!!.notifyDataSetChanged()
}
}
和適配器MoviesRecyclerAdapter:
class MoviesRecyclerAdapter(private val moviesList: List<Movies>) : RecyclerView.Adapter<MoviesRecyclerAdapter.MyViewHolder>() {
class MyViewHolder(view: View ) : RecyclerView.ViewHolder(view) ,View.OnClickListener {
var title: TextView = view.findViewById<TextView>(R.id.title)
var year: TextView = view.findViewById<TextView>(R.id.year)
var genre: TextView = view.findViewById<TextView>(R.id.genre)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val itemView = LayoutInflater.from(parent.context)
.inflate(R.layout.movie_list_row, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val Movies = moviesList[position]
holder.title.text = Movies.title
holder.genre.text = Movies.genre
holder.year.text = Movies.year
}
override fun getItemCount(): Int {
return moviesList.size
}
}
我需要當用戶單擊列表中的項目可打開的其他活動,什麼是清潔和最佳這樣做的方式。