我正在尝试理解并将java代码翻译成kotlin。该代码可用here。
基本上有两个类文件
DeviceListActivity
:允许用户从ListView中选择item
SerialConsoleActivity
:对选定的item
执行读/写操作 DeviceListActivity
的相关代码部分如下:
private void showConsoleActivity(UsbSerialPort port) {
SerialConsoleActivity.show(this, port);
}
来自SerialConsoleActivity
的相关代码片段如下:
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
的静态方法SerialConsoleActivity
如何能够保留port
对象的传递?没有& #39; t所涉及的父类的实例(这也是静态方法的全部目的)。
为了达到与上面类似的效果,我编写了以下代码,但它不起作用:
class MainActivity : AppCompatActivity() {
var sPort :UsbSerialPort?=null
private val GET_AVAILABLE_USB_DEVICE = 1
companion object {
const val PORT = "port"
fun show(context: Context, port: UsbSerialPort) {
sPort = port
}
}
无法从节目内部访问sPort。
如果我将show
函数移到配套对象之外,
然后我不能做以下
MainActivity.show(this, port_obj)
&#34;狡猾的黑客&#34;原帖中的警告建议通过传递参数来重新创建驱动程序,但唉,它是not clear how would one create an port object from arguments。
另一种选择是实现一个可序列化的对象(因为端口尚不可序列化)并通过意图传递它,但我还不熟悉序列化。因此,我正在寻找类似于&#34; kotlin&#39; y&#34;中原始作品的类似解决方法。请帮助。
答案 0 :(得分:0)
如果您希望移植旧的静态sPort
,则需要将其添加到您的随播广告,协同对象也可以替代静态方法和属性。
companion object {
const val PORT = "port"
UsbSerialPort sPort = null;
fun show(context: Context, port: UsbSerialPort) {
sPort = port
}
}