Frage

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.

War es hilfreich?

Lösung 2

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

Andere Tipps

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       
    }
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top