Tom Xue
Tom Xue

Reputation: 3355

Why 'this' can be used as the argument here in Java?

public class Activity01 extends Activity implements OnClickListener,
        ViewFactory {
        ...
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            LinearLayout main_view = new LinearLayout(this);
            m_Switcher = new ImageSwitcher(this);
            main_view.addView(m_Switcher);
            m_Switcher.setId(SWITCHER_ID);
            m_Switcher.setFactory(this);
            m_Switcher.setOnClickListener(this);
            setContentView(main_view);
            ...
        }

        public void onClick(View v) {
            ...
        }
    }

Above code is from an Android project, and below function's argument is set as 'this', why?

m_Switcher.setOnClickListener(this);

According to the javadoc, here should be like below:

public void setOnClickListener (View.OnClickListener l)

That means the argument should be this kind: View.OnClickListener

So why 'this' can be there? Thanks!

Note: According to the answers, I gave a more complete code above.

Upvotes: 1

Views: 117

Answers (1)

lynks
lynks

Reputation: 5689

In the class declaration you will find it either extends or implements OnClickListener. That means that the class can be used as an OnClickListener (because it is one, amongst other things). That is why you can use this here.

Upvotes: 7

Related Questions