0
btnOpen.setOnClickListener(new OnClickListener() 
{ 
  public void onClick(View v) 
      { 
             Toast.makeText(getBaseContext(), 
             "Time selected:" +  
             timePicker.getCurrentHour() +  
             ":" + timePicker.getCurrentMinute(), 
             Toast.LENGTH_SHORT).show(); 
       } 
}); 

How to convert this to non-anonymous inner class?

Lukas Knuth
  • 25,449
  • 15
  • 83
  • 111
sanjay
  • 2,116
  • 3
  • 19
  • 25

2 Answers2

1

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • The nested class would need to be declared as private class InnerOnClickListener extends OnClickListener – Brett Walker Aug 06 '11 at 07:44
  • @Brett: Isn't it an interface? Hence implements, not extends. (I corrected my original for that a couple of minutes ago.) – Jon Skeet Aug 06 '11 at 07:45
  • Thanks Jon. I saw something was a miss. Tried to be helpful. – Brett Walker Aug 06 '11 at 07:47
  • private class InnerOnClickListener implements OnClickListener /private class InnerOnClickListener extends OnClickListener – sanjay Aug 06 '11 at 07:47
  • @skbishi: I don't understand the point your comment was trying to make. Were you asking which you should be using? – Jon Skeet Aug 06 '11 at 07:53
  • its ok i got it..... jon thx.. (interface are all ways implements) am i right...? – sanjay Aug 06 '11 at 07:56
  • @Brett: Sorry, that wasn't meant to sound grumpy. I wasn't sure whether you'd seen my correction to make it implement the interface, and were trying to tell me that it should extend it as a class instead, or whether you just hadn't seen my edit. It can get a bit confusing with overlapping edits/comments. – Jon Skeet Aug 06 '11 at 08:12
0

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();
        }
    }
}
basicsharp
  • 446
  • 3
  • 8