#android #kotlin #android-fragments #android-recyclerview #android-adapter
Вопрос:
Основная деятельность
class MainActivity : AppCompatActivity(), MovieListAdapter.ItemClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.beginTransaction().apply {
add(R.id.flMain, FragmentMovieList())
commit()
}
}
override fun onItemClick() {
supportFragmentManager.beginTransaction().apply {
replace(R.id.flMain, FragmentMoviesDetails())
addToBackStack(null)
.commit()
}
}
}
Первый адаптерный
class MovieListAdapter: RecyclerView.Adapter<MovieListAdapter.ViewHolder>() {
private var list = listOf<Movie>()
private var itemclick: ItemClickListener? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_holder_movie,parent,false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val movie = list[position]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.avatar?.setImageDrawable(holder.itemView.context.getDrawable(movie.avatar))
holder.years?.text = movie.years
holder.heart?.setImageDrawable(holder.itemView.context.getDrawable(movie.heart_avatar))
holder.genre?.text = movie.genre
holder.star1?.setImageDrawable(holder.itemView.context.getDrawable(movie.star1))
holder.star2?.setImageDrawable(holder.itemView.context.getDrawable(movie.star2))
holder.star3?.setImageDrawable(holder.itemView.context.getDrawable(movie.star3))
holder.star4?.setImageDrawable(holder.itemView.context.getDrawable(movie.star4))
holder.star5?.setImageDrawable(holder.itemView.context.getDrawable(movie.star5))
holder.review?.text = movie.reviews
holder.name?.text = movie.name
holder.time?.text = movie.time
holder.rvActor?.apply { setOnClickListener{
itemclick?.onItemClick()
} }
}
}
fun bindActors(newMovie: List<Movie>) {
list = newMovie
notifyDataSetChanged()
}
override fun getItemCount(): Int = list.size
class ViewHolder(view: View): RecyclerView.ViewHolder(view){
val avatar: ImageView? = itemView.findViewById(R.id.ivMain)
val years: TextView? = itemView.findViewById(R.id.tvYears)
val heart: ImageView? = itemView.findViewById(R.id.ivHeart)
val genre: TextView? = itemView.findViewById(R.id.tvGenre)
val star1: ImageView? = itemView.findViewById(R.id.ivStar1)
val star2: ImageView? = itemView.findViewById(R.id.ivStar2)
val star3: ImageView? = itemView.findViewById(R.id.ivStar3)
val star4: ImageView? = itemView.findViewById(R.id.ivStar4)
val star5: ImageView? = itemView.findViewById(R.id.ivStar5)
val review: TextView? = itemView.findViewById(R.id.tvReviews)
val name: TextView? = itemView.findViewById(R.id.tvName)
val time: TextView? = itemView.findViewById(R.id.tvTime)
val rvActor: RecyclerView? = itemView.findViewById(R.id.rvActors)
}
interface ItemClickListener{
fun onItemClick()
}
}
Второй адаптерный
class MovieDetailAdapter: RecyclerView.Adapter<MovieDetailAdapter.ViewHolder>() {
private var listDetail = listOf<MovieDetail>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.view_holder_actor, parent, false)
)
}
override fun onBindViewHolder(holder: MovieDetailAdapter.ViewHolder, position: Int) {
val detail = listDetail[position]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.imageDetail?.setImageDrawable(holder.itemView.context.getDrawable(detail.imageDetail))
holder.detailName?.text = detail.detailName
holder.detailAge?.text = detail.detailAge
holder.tag?.text = detail.tag
holder.detailStar1?.setImageDrawable(holder.itemView.context.getDrawable(detail.detailStar1))
holder.detailStar2?.setImageDrawable(holder.itemView.context.getDrawable(detail.detailStar2))
holder.detailStar3?.setImageDrawable(holder.itemView.context.getDrawable(detail.detailStar3))
holder.detailStar4?.setImageDrawable(holder.itemView.context.getDrawable(detail.detailStar4))
holder.detailStar5?.setImageDrawable(holder.itemView.context.getDrawable(detail.detailStar5))
holder.detailReviews?.text = detail.detailReviews
holder.detailStory?.text = detail.story.toString()
holder.actor1?.setImageDrawable(holder.itemView.context.getDrawable(detail.actor1))
holder.actor2?.setImageDrawable(holder.itemView.context.getDrawable(detail.actor2))
holder.actor3?.setImageDrawable(holder.itemView.context.getDrawable(detail.actor3))
holder.actor4?.setImageDrawable(holder.itemView.context.getDrawable(detail.actor4))
holder.nameActor1?.text = detail.nameActor1
holder.nameActor2?.text = detail.nameActor2
holder.nameActor3?.text = detail.nameActor3
holder.nameActor4?.text = detail.nameActor4
}
}
fun bindActorsDetail(newDetail: List<MovieDetail>) {
listDetail = newDetail
notifyDataSetChanged()
}
override fun getItemCount(): Int = listDetail.size
class ViewHolder(view: View): RecyclerView.ViewHolder(view){
val imageDetail: ImageView? = itemView.findViewById(R.id.imageDetail)
val detailName: TextView? = itemView.findViewById(R.id.detailName)
val detailAge: TextView? = itemView.findViewById(R.id.yearsDetail)
val tag: TextView? = itemView.findViewById(R.id.tag)
val detailStar1: ImageView? = itemView.findViewById(R.id.detailStar1)
val detailStar2: ImageView? = itemView.findViewById(R.id.detailStar2)
val detailStar3: ImageView? = itemView.findViewById(R.id.detailStar3)
val detailStar4: ImageView? = itemView.findViewById(R.id.detailStar4)
val detailStar5: ImageView? = itemView.findViewById(R.id.detailStar5)
val detailReviews: TextView? = itemView.findViewById(R.id.detailReviews)
val detailStory: TextView? = itemView.findViewById(R.id.detailStory)
val actor1: ImageView? = itemView.findViewById(R.id.ivDetail1)
val actor2: ImageView? = itemView.findViewById(R.id.ivDetail2)
val actor3: ImageView? = itemView.findViewById(R.id.ivDetail3)
val actor4: ImageView? = itemView.findViewById(R.id.ivDetail4)
val nameActor1: TextView? = itemView.findViewById(R.id.tvDetail1)
val nameActor2: TextView? = itemView.findViewById(R.id.tvDetail2)
val nameActor3: TextView? = itemView.findViewById(R.id.tvDetail3)
val nameActor4: TextView? = itemView.findViewById(R.id.tvDetail4)
}
}
FirstFragment
class FragmentMovieList : Fragment() {
private var recycler: RecyclerView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_movie_list, container, false)
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
recycler = view.findViewById(R.id.rvActors)
recycler?.adapter = MovieListAdapter()
}
override fun onStart() {
updateData()
super.onStart()
}
private fun updateData() {
(recycler?.adapter as? MovieListAdapter)?.apply {
bindActors(MovieData().getMovie())
}
}
}
Второй фрагмент
class FragmentMoviesDetails : Fragment() {
private var recyclerDetail: RecyclerView? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_movies_details, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
recyclerDetail = view.findViewById(R.id.rvDetail)
recyclerDetail?.adapter = MovieDetailAdapter()
}
override fun onStart() {
updateData()
super.onStart()
}
private fun updateData() {
(recyclerDetail?.adapter as? MovieDetailAdapter)?.apply {
bindActorsDetail(DetailData().getDetail())
}
}
}
Я использую список с некоторыми данными для первого адаптера и второго.
Я сделал некоторые действия, чтобы при нажатии на значок в первом фрагменте перейти ко второму фрагменту, но ничего не появилось.
Без recyclerview.adapter
переходов между фрагментами не обошлось
Ответ №1:
Я также реализовал то же самое, т. е. открыл другой фрагмент из фрагмента с видом переработчика с помощью компонента навигации. Я могу поделиться своим кодом, чтобы вы могли получить некоторые ссылки. Итак, вот мой код…
Адаптер
class TheoryAdapter(private var mlistner : onItemClickListener): RecyclerView.Adapter<TheoryAdapter.ViewHolder>() {
interface onItemClickListener{
fun onItemClick(position: Int)
}
//my code (create amp; bind view holder)
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),View.OnClickListener {
//my code
init {
itemView.setOnClickListener(this)
}
override fun onClick(v: View?) {
val position = bindingAdapterPosition
if (position!=RecyclerView.NO_POSITION) {
if (v != null) {
mlistner.onItemClick(position)
}
}
}
}
}
Фрагмент
class TheoryFragment : Fragment(R.layout.fragment_theory),TheoryAdapter.onItemClickListener {
//my code (onCreateView)
override fun onItemClick(position: Int) {
val pos = position
val action = TheoryFragmentDirections.actionTheoryFragmentToTextDisplayFragment(pos)
findNavController().navigate(action)
}
}
Навигационный график
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@ id/nav_graph.xml"
app:startDestination="@id/mainFragment">
<fragment
android:id="@ id/theoryFragment"
android:name="com.example.learnjava.fragment.TheoryFragment"
android:label="fragment_theory"
tools:layout="@layout/fragment_theory" >
<action
android:id="@ id/action_theoryFragment_to_textDisplayFragment"
app:destination="@id/textDisplayFragment" />
</fragment>
</navigation>
Комментарии:
1. Извините, но я не могу понять, откуда у вас такие методы, как теория фрагментных директорий.actionTheoryFragmentToTextDisplayFragment или привязка к адаптеру, и как вы используете этот метод при нажатии
2. TheoryFragmentDirections.actionTheoryFragmentToTextDisplayFragment , это для перехода от основного фрагмента к другому фрагменту, я предлагаю вам посмотреть видео на навигационном компоненте, это действительно простой способ переключения между фрагментами. И метод onClick исходит от адаптера.