开发者

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();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜