what is the substitute for this anonymous inner class?
btnOpen.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
"Time selected:" +
timePicker.getCurrentHo开发者_C百科ur() +
":" + timePicker.getCurrentMinute(),
Toast.LENGTH_SHORT).show();
}
});
How to convert this to non-anonymous inner class?
You'd simply need to make it an inner class:
btnOpen.setOnClickListener(new InnerOnClickListener());
...
private class InnerOnClickListener implements OnClickListener
{
public void onClick(View v)
{
Toast.makeText(getBaseContext(),
"Time selected:" +
timePicker.getCurrentHour() +
":" + timePicker.getCurrentMinute(),
Toast.LENGTH_SHORT).show();
}
}
Note the use of getBaseContext()
which will actually be called on the instance of the creating class.
If timePicker
is a local variable in your method (as opposed to an instance variable in the creating class) you'd need to pass that into a constructor of the inner class.
You should declare an View.OnClickListener interface implementation:
btnOpen.setOnClickListener(buttonClickListener);
...
private View.OnClickListener buttonClickListener = new View.OnClickListener() {
@Overide
public void onClick(View v) {
Toast.makeText(getBaseContext(),
"Time selected:" +
timePicker.getCurrentHour() +
":" + timePicker.getCurrentMinute(),
Toast.LENGTH_SHORT).show();
}
}
}
精彩评论