Stranger 2020-05-30
在Android中声明UI类型变量,由于Kotlin的类型安全机制必须进行初始化,比如:
Java:
public class TestActivity extends AppCompatActivity { private TextView mTvNmae; @Override protected void OnCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTvNmae = findViewById(R.id.name); } }
Kotlin:
解决方法1 初始化为Null:
class MainActivity : AppCompatActivity() { private var mTvName: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mTvName = findViewById(R.id.name) } }
初始化问题解决了,但是使用上非常不友好。
解决方法2 延迟初始化:
class MainActivity : AppCompatActivity() { private lateinit var mTvName: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mTvName = findViewById(R.id.name) } }
这方式也解决了初始化问题,就是mTvName是一个可变类型变量,在初始化后基本上不会改变变量的赋值了。
解决方法3 延迟初始化 lazy (推荐方式):
class MainActivity : AppCompatActivity() { private val mTvName: TextView by lazy { findViewById(R.id.name) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }