Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App Basic Android Programming Adding the OnClick Method

Sahar Nasiri
Sahar Nasiri
7,454 Points

View.OnClickListener Outside the onCreate method

I wrote the View.OnClickListener like this:

package sahar.funfacts;

import...

public class FunFactsActivity extends AppCompatActivity {

    // Declare our View variables
    private TextView mFactTextView;
    private Button mShowFactButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fun_facts);

        // Assign the Views from thel layout file to the corresponding variables
        mFactTextView = (TextView)findViewById(R.id.factTextView);
        mShowFactButton = (Button)findViewById(R.id.showFactButton);


        mShowFactButton.setOnClickListener(listener);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    };
}

Is this a problem to write this method outside the OnCreate method? Why did he write it there?

1 Answer

Seth Kroger
Seth Kroger
56,413 Points

Either way works. Here it's being stored in a field. That can be useful if a reference to the listener is needed later, but not necessary.

There are several other styles of dealing with the listener as well, each of which isn't inherently better than the others.