Kotlin之类属性延迟初始化
类属性延迟初始化
在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) } }
相关推荐
worldsnow 2020-11-06
csdnxingyuntian 2020-11-02
丽丽 2020-10-30
bluecarrot 2020-09-17
哈嘿Blog 2020-08-16
qidiantianxia 2020-08-16
84931231 2020-07-30
ChenRuiyz 2020-07-26
yanqianglifei 2020-07-07
wbczyh 2020-07-05
BOBShe 2020-07-03
yang0cs 2020-06-28
fushilin 2020-06-28
清水寺小僧 2020-06-25
uileader 2020-06-21
wangyangsoftware 2020-06-16
cleanerxiaoqiang 2020-06-16
xuguiyi00 2020-06-14