2017-06-01 77 views
0

我怎么能在Kotlin上有这样的java代码? 即使IDE不会完全将其转换为Kotlin!如何在我的Kotlin类中创建一个匿名接口实现并使用它?

/** Defines callbacks for service binding, passed to bindService() */ 
private ServiceConnection mConnection = new ServiceConnection() { 

    @Override 
    public void onServiceConnected(ComponentName className, 
      IBinder service) { 
     // We've bound to LocalService, cast the IBinder and get LocalService instance 
     LocalBinder binder = (LocalBinder) service; 
     mService = binder.getService(); 
     mBound = true; 
    } 

    @Override 
    public void onServiceDisconnected(ComponentName arg0) { 
     mBound = false; 
    } 
}; 

我尝试使用inner class但当时我没能像这样使用:

@Override 
protected void onStart() { 
    super.onStart(); 
    // Bind to LocalService 
    Intent intent = new Intent(this, LocalService.class); 
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE); 
} 

回答

6

你在这里创建一个匿名类。在Kotlin,这些是:

val connection = object: ServiceConnection() { 
    override fun onServiceConnected(className: ComponentName, service: IBinder) { 
     ... 
    } 

    override fun onServiceDisconnected(arg0: ComponentName) { 
     ... 
    } 
} 
+0

非常感谢!它为我工作。 –

相关问题