Anshuman Pattnaik
Anshuman Pattnaik

Reputation: 933

How to add the OnClickListener Object in Android?

I am going through an error. Not able to add the OnClickListener object. This is following code.

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) 
    {


        Activity act;

        View rootView = inflater.inflate(R.layout.abc, container, false);

        TextView tt=(TextView) rootView.findViewById(R.id.txt);

        Button button=(Button) rootView.findViewById(R.id.btn1);


        button.setOnClickListener(mFan); // Here i am getting the error //

        View.OnClickListener mFan = new OnClickListener() 
        {

            public void onClick(View v) 
            {


            }

        };

   }

I am facing error in mFan OnClickListener object ,

I am getting an error of mFan cannot be resolved to a variable

So, please help me out , suggest me with some good solution.

Upvotes: 0

Views: 2425

Answers (2)

Tyler MacDonell
Tyler MacDonell

Reputation: 2629

You need to declare your OnClickListener before you reference it...

View.OnClickListener mFan = new OnClickListener() 
{
     public void onClick(View v) 
     {
         // stuff
     }
};

button.setOnClickListener(mFan);

You also need your onCreateView method to return a View, so don't forget:

return rootView;

at the bottom of your onCreateView method...

As a side note, you can accomplish the same thing using an anonymous listener like this:

button.setOnClickListener(new OnClickListener(){
    @Override
    public void onClick(View v) {
        // your stuff       
    }
});

Upvotes: 3

Jorgesys
Jorgesys

Reputation: 126533

first you have to create the listener,

View.OnClickListener mFan = new OnClickListener(){
     public void onClick(View v) 
     {
     }
};

and then that you have created an OnClickListener now set to your button.

button.setOnClickListener(mFan);

Upvotes: 1

Related Questions