我可以写sampleVideoView吗? =在Kotlin中的findViewById (R.id.videoView)?

下面的代码是来自Kotlin示例项目,我想我总是可以写sampleVideoView? = findViewById(R.id.videoView) sampleVideoView? = findViewById(R.id.videoView) ,对不对?

和更多

代码sampleVideoView?.setVideoURI(Uri.parse(HLS_STREAMING_SAMPLE))if (sampleVideoView!=null){sampleVideoView.setVideoURI(Uri.parse(HLS_STREAMING_SAMPLE))}是等价的,对不对?

  class MainActivity : AppCompatActivity(){ private var sampleVideoView: VideoView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) sampleVideoView = findViewById(R.id.videoView) sampleVideoView?.setVideoURI(Uri.parse(HLS_STREAMING_SAMPLE)) ... 

sampleVideoView? = findViewById(R.id.videoView)

这不是有效的语法。 这个? 用于将types标记为可为空,并安全地访问包含这些可空types的variables。

代码sampleVideoView?.setVideoURI(Uri.parse(HLS_STREAMING_SAMPLE))与if(sampleVideoView!= null){sampleVideoView.setVideoURI(Uri.parse(HLS_STREAMING_SAMPLE))}是等价的,对不对?

真正。 但是,如果你有例如val x = y?.getName()variablesx将为null或者包含y之后的名字。 这不仅仅是“如果!= null ”,你的例子可以建议。

你可以忘记findView方法,并用kotlin android扩展插件替换它

 apply plugin: 'kotlin-android-extensions' 

之后,你可以写:

yourVideoViewID.setVideoURI(Uri.parse(HLS_STREAMING_SAMPLE))

以下是将可为空的值赋给可为空的variables的正确语法。 在作业中不需要问号

  sampleVideoView = findViewById(R.id.videoView) 

第二个陈述是等价的