How exactly does the android:onClick XML attribute differ from setOnClickListener?

后端 未结 17 2501
野趣味
野趣味 2020-11-21 11:50

From that I\'ve read you can assign a onClick handler to a button in two ways.

Using the android:onClick XML attribute where you just use t

17条回答
  •  滥情空心
    2020-11-21 12:08

    Be careful, although android:onClick XML seems to be a convenient way to handle click, the setOnClickListener implementation do something additional than adding the onClickListener. Indeed, it put the view property clickable to true.

    While it's might not be a problem on most Android implementations, according to the phone constructor, button is always default to clickable = true but other constructors on some phone model might have a default clickable = false on non Button views.

    So setting the XML is not enough, you have to think all the time to add android:clickable="true" on non button, and if you have a device where the default is clickable = true and you forget even once to put this XML attribute, you won't notice the problem at runtime but will get the feedback on the market when it will be in the hands of your customers !

    In addition, we can never be sure about how proguard will obfuscate and rename XML attributes and class method, so not 100% safe that they will never have a bug one day.

    So if you never want to have trouble and never think about it, it's better to use setOnClickListener or libraries like ButterKnife with annotation @OnClick(R.id.button)

提交回复
热议问题