Search code examples
androidbuttonviewonclicklistenerandroid-inflate

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.


Solution

  • 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);