将静态方法从java转换为kotlin时出现的问题
我试图理解java代码并将其翻译成kotlin。代码是可用的 基本上有两个类文件将静态方法从java转换为kotlin时出现的问题,java,android,kotlin,Java,Android,Kotlin,我试图理解java代码并将其翻译成kotlin。代码是可用的 基本上有两个类文件 DeviceListActivity:允许用户从列表视图中选择项 SerialConsoleActivity:对选定的项执行读/写操作 DeviceListActivity中的相关代码部分如下: private void showConsoleActivity(UsbSerialPort port) { SerialConsoleActivity.show(this, port); } p
DeviceListActivity
:允许用户从列表视图中选择项
SerialConsoleActivity
:对选定的项执行读/写操作
DeviceListActivity
中的相关代码部分如下:
private void showConsoleActivity(UsbSerialPort port) {
SerialConsoleActivity.show(this, port);
}
public class SerialConsoleActivity extends Activity {
private final String TAG = SerialConsoleActivity.class.getSimpleName();
/**
* Driver instance, passed in statically via
* {@link #show(Context, UsbSerialPort)}.
*
* <p/>
* This is a devious hack; it'd be cleaner to re-create the driver using
* arguments passed in with the {@link #startActivity(Intent)} intent. We
* can get away with it because both activities will run in the same
* process, and this is a simple demo.
*/
private static UsbSerialPort sPort = null;
...
//more code
...
static void show(Context context, UsbSerialPort port) {
sPort = port;
final Intent intent = new Intent(context, SerialConsoleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}
}
SerialConsoleActivity
中的相关代码片段如下:
private void showConsoleActivity(UsbSerialPort port) {
SerialConsoleActivity.show(this, port);
}
public class SerialConsoleActivity extends Activity {
private final String TAG = SerialConsoleActivity.class.getSimpleName();
/**
* Driver instance, passed in statically via
* {@link #show(Context, UsbSerialPort)}.
*
* <p/>
* This is a devious hack; it'd be cleaner to re-create the driver using
* arguments passed in with the {@link #startActivity(Intent)} intent. We
* can get away with it because both activities will run in the same
* process, and this is a simple demo.
*/
private static UsbSerialPort sPort = null;
...
//more code
...
static void show(Context context, UsbSerialPort port) {
sPort = port;
final Intent intent = new Intent(context, SerialConsoleActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
context.startActivity(intent);
}
}
不能从展会内部接触运动项目
如果我将show
函数移到同伴对象之外
那么我就不能做以下事情了
MainActivity.show(this, port_obj)
原始帖子中的“恶意黑客”警告建议通过传递参数来重新创建驱动程序,但遗憾的是,事实并非如此
另一个选项是实现一个可序列化对象(因为端口还不可序列化),并通过intent传递它,但我还不熟悉序列化。因此,我正在寻找一个类似的工作做了在原来的工作在“kotlin'y的方式”。请提供帮助。如果您想移植旧的静态
sPort
您需要将其添加到您的companion中,companion对象也可以替代静态方法和属性
companion object {
const val PORT = "port"
UsbSerialPort sPort = null;
fun show(context: Context, port: UsbSerialPort) {
sPort = port
}
}
创建
intent
并启动父活动如何?可以将它放在show
方法中吗?您也可以这样做来启动您的意图,这里没有任何更改