如何使用kotlin在android中初始化小部件
我已经开始学习在android中使用kotlin语言,并在初始化我的按钮变量时得到问题,因为在定义我的变量的时候,它要求给予一些初始值,当我用null值初始化,并绑定变量oncreate函数它的给
kotlin.KotlinNullPointerException
这是我的代码
class AddsFragment : Fragment() { var Add: Button = null!! override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val Rootview = inflater!!.inflate(R.layout.clubsfragment, null, false) Add = Rootview.findViewById(R.id.add) as Button return Rootview } }
!!
运算符检查接收者是否为null
,是否抛出KotlinNullPointerException
。 null!!
总是会抛出一个异常。
你可以通过以下方式实现你想要的:
-
将属性的类型设置为
Button?
。 在这种情况下访问按钮的方法时,你将不得不使用?
或!!
。var add: Button? = null // Initialize it somewhere. add?.setText("Text") // Calls setText if Add != null add!!.setText("Text") // Throws an exception if Add == null
-
使按钮成为
lateinit
属性。lateinit var add: Button
-
使按钮成为一个
notNull
委托属性。var add: Button by Delegates.notNull()
在最后两种情况下,您不能检查按钮是否为null
。 如果你需要使用null
比较来为变量使用第一种方法。
还有另一种方法,我不会在这个答案中详细描述。 第一个是使用Kotlin Android扩展 。 这是一个编译器插件,为您的视图生成综合属性,所以您不需要调用findViewById()
并可以使用生成的属性访问视图。
第二种方法是创建您自己的委托,为您调用findViewById()
。 它可能看起来像这样:
val add: Button by bindView(R.id.add)
您可以在KotterKnife项目中找到这样的代表的例子 。
您可以使用Kotlin编写帮助bind
函数:
fun <T : View> Activity.bind(@IdRes res : Int) : Lazy<T> { @Suppress("UNCHECKED_CAST") return lazy { findViewById(res) as T } }
然后,你可以简单地使用val
(等于Java中的final
)来定义你的变量:
class MyActivity : AppCompatActivity() { private val button: Button by bind(R.id.button) }
要么
class MyActivity : AppCompatActivity() { private val button by bind<Button>(R.id.button) }
您可以使用以下任何一种方法初始化kotlin中的视图:
可空的变量
private var textView: TextView? = null … textView = findViewById(R.id.text_view) as TextView
2.迟到
private lateinit var textView: TextView … textView = findViewById(R.id.text_view) as TextView
3. Delegates.notNull()
private var textView: TextView by Delegates.notNull() … textView = findViewById(R.id.text_view) as TextView
4.懒惰的属性
private val textView: TextView by lazy { findViewById(R.id.text_view) as TextView }
5.切割刀
@BindView(R2.id.text_view) internal lateinit var textView: TextView
6. Kotterknife
private val textView: TextView by bindView(R.id.text_view)
7. Kotlin Android扩展
没有代码示例,只是得到正确的导入添加,并开始使用像下面的合成生成的属性。
import kotlinx.android.synthetic.main.<layout>.*
8. Android数据绑定
binding = FragmentLayoutBinding.inflate(inflater, container, false) ... binding.textView.text = "Hello"
您可以在Android视图访问策略的优缺点检查每种方法的pro / cons