Search code examples
javaandroidfindviewbyid

Trying to implement onClickListener in seperate class but findViewById cannot be resolved


I am trying to create a separate class to implement the onClickListeners for my buttons and EditTexts, but I keep getting an error saying findViewById cannot be resolved. I have inserted the code below:

package com.example.afa.geobuddy;

import android.view.View;
import android.widget.Button;
public class onClickListener implements View.OnClickListener {
    Button cancel_button = (Button) findViewById(R.id.btn_cancel);
    @Override
    public void onClick(View v) {

    }
}

Solution

  • This happends because findViewById method is a member of android.app.Activity class, i.e. it is only visible from the anonymous class inside Activity. So in order to define your onClickListener in a separate class you should pass view to it, smth like this:

    public class MyOnClickListener implements View.OnClickListener {
    
        @Override
        public void onClick(View v) {
    
        }
    }
    

    and somewhere in your activity:

    Button button = (Button) findViewById(R.id.btn_cancel)
    button.setOnClickListener(new MyOnClickListener());