I have the following Java code:
public class FirstActivity extends Activity implements OnClickListener
{
Button btn;
TextView textview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView)findViewById(R.id.textView2);
btn = (Button)findViewById(R.id.BtnGoToSecondActivity);
btn.setOnClickListener(this);
}
public void onClick(View v)
{
Intent secondActivityIntent = new Intent(this, SecondActivity.class);
secondActivityIntent.putExtra("Name", textview.getText());
startActivity(secondActivityIntent);
}
}
Every bit of code makes sense until I hit the “this” keyword in the example above.
I can’t get my head around the “this” keyword used as an argument in the “setOnClickListener()” method call..
I haven’t created an instance of any of the used classes above. How can I refer to an instance that is non-existing? Is the instance created automatically?
(I know what the “this” keyword is and what it does, but in this case I don’t see the logic)
Basically, this line of code:
… is stating that the event listener for the button, is the same instance you’re currently on – given that the class it belongs to (
FirstActivity) implements theOnClickListenerinterface.And yes, there is an instance already created when you call this method, otherwise you wouldn’t be able to call the method at all! You happen to be passing as an argument to
setOnClickListenerthe current instance you’re on at the time of invoking theonCreate()method.