Home > OS >  I could not connect my recyclerview in fragment with adapter
I could not connect my recyclerview in fragment with adapter

Time:02-26

my fragment class

class RecyclerFragment : Fragment() {
var recycler:RecyclerView? =null

private var param1: String? = null
private var param2: String? = null


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    recycler = view?.findViewById(R.id.recycler)

    }


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_recycler, container, false)
}

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    recycler?.layoutManager = LinearLayoutManager(this.context,RecyclerView.VERTICAL,false)


    recycler?.adapter = Custom_Adapter() // error-Unresolved reference: Custom_Adapter


}


}

//here is my adater

 class Custom_Adapter() : RecyclerView.Adapter<Custom_Adapter.ViewHolder>() {


override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): Custom_Adapter.ViewHolder {
 var myViewInflater = LayoutInflater.from(viewGroup.context).inflate(R.layout.custom_layout,viewGroup,false)
    return ViewHolder(myViewInflater)
}

override fun onBindViewHolder(holder: Custom_Adapter.ViewHolder, position: Int) {

}

override fun getItemCount(): Int {
    return 9

}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

}
}

CodePudding user response:

Use like this

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

    }


override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment

  val view = inflater.inflate(R.layout.fragment_recycler, container, false)
  recycler = view?.findViewById(R.id.recycler)
    return  view 
}

CodePudding user response:

From your repo link in one of the comments, Custom_Adapter is under your src/test directory. It needs to be under src/main where RecyclerFragment can see it - that's why you're getting unresolved reference errors. Stick it in there with everything else

main and test are different source sets, it's basically a way of keeping stuff separate. All your production code goes in main, and it can't see anything in test by default. When you run tests, those use everything in test (and maybe androidTest) and get all the stuff in main included, since the tests need access to the production code to, y'know, test it!

  • Related