Reputation: 31
I am trying to figure out why I can't access the setOnClickListener()
outside the onCreate()
method.
The following code snippet is placed below the onCreate()
method.
TextView numbers = (TextView)findViewById(R.id.numbers);
numbers.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumbersActivity.class);
startActivity(intent);
}
});
I am trying to set EventListener to a TextView
, but setOnClickListener
appears in a red line. Why is this happening? I mean if I place the code snippet inside the onCreate()
method it's working. Why I can't access the setOnClickListener
from outside?
Upvotes: 0
Views: 73
Reputation: 4470
Because those are one of the programming language rules. Outside of a method or function you can declare static blocks, declare other functions or make assignment. setOnClickListener
is a method which accepts as an argument interface
and looks something like this:
public interface OnClickListener {
void onClick(View v);
}
And actually there are couple implementations. One of them you have used above in example, second one is to implement View.OnClickListener
interface and override method onClick(View view)
now you can subscribe your views to this interface numbers.setOnClickListener(this)
and if you have more than one view subscribed you can distinguish between them inside onClick(View view)
by checking for id
like:
public void onClick(View view){
switch(view.getId()){
case R.id.numbers:
break;
}
}
And there is one more implementation which would look like this:
public OnClickListener onClick = new OnClickListener() {
@Override
public void onClick(View v) {
}
};
Now you can use: numbers.setOnClickListener(onClick)
Upvotes: 0
Reputation: 2431
You can't access view out side its bounded area here onCreate()
method's bound. If you want that then you have to inflate the view by layout-inflater
.
Upvotes: 1