skip to Main Content

I simply made an adapter for my recyclerview.like this :

class CustomerAdapter(mCtx:Context,val customers:ArrayList<Customer>):RecyclerView.Adapter<CustomerAdapter.ViewHolder>(){

and i have a xml layout file to inflate recycleview items.

But the problem is in onCreateViewHolder … I can not access inflated elements …

codes writed in my onCreateViewHolder method :

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomerAdapter.ViewHolder {
        val v = LayoutInflater.from(parent.getContext()).inflate(R.layout.lo_customers, parent, false);
        var txt = v.id

    }

i can not access view elements by id .

enter image description here

4

Answers


  1. Chosen as BEST ANSWER

    At gradle app

    plugins {
       id 'kotlin-android-extensions'
    }
    

    Or

    apply plugin: 'kotlin-android-extensions'
    

    Then your Activity Import this

    import kotlinx.android.synthetic.main.activity_main.*
    

  2. Even if you capture the View, you cannot directly access the children’s in the View. In-order to get hold of children’s you need to use
    findViewById(R.id.my_textView_id) on the View object.

    Hence replace your v.txt by v.findViewById(R.id.my_text_view_id).

    Login or Signup to reply.
  3. This is completely the wrong way to do it . onCreateViewHolder the function name itself says that it is meant only for inflating the view and doing nothing else. It should only be used for creating the ViewHolder . Even if you inflate your view and assign view from there , it is going to crash in the future . You have to inflate the view there and pass the parent view to another class which should extend RecyclerView.ViewHolder() .

    So do it the following way :

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CustomerAdapter.ViewHolder {
            val v = LayoutInflater.from(parent.getContext()).inflate(R.layout.lo_customers, parent, false);
       
        }
    

    Create an ViewHolder Class extending RecyclerView.ViewHolder :

     class CustomViewHolder(val view: View) :
            RecyclerView.ViewHolder(view) {
            fun bind(model  : Model) {
    
             //Now here you can access all the components present in your layout in the following way and do the stuff you want with them: 
               val text = view.findViewById(R.id.viewid)
            }
        }
    
    Login or Signup to reply.
  4. Try not to access from android.R, rather try like this:

    CategoryAdapterHolder(LayoutInflater.from(parent.context).inflate(com.example.secondhand.R.layout.category_list, parent, false))

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search