I want to attach a View.OnClickListener
to a Button
. I don't want the OnClickListener
to be an inline anonymous function definition. Rather, I want to define it outside the bounds of the onCreateView()
function.
In Java, I would do this as follows:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.my_layout, container, false);
View my_btn = view.findViewById(R.id.my_btn);
my_btn.setOnClickListener(handleButtonClick);
return view;
}
View.OnClickListener handleButtonClick = new View.OnClickListener()
{
@Override public void onClick(View v)
{
Log.d("my_tag", "click!")
}
}
Other answers seems to suggest the following will work, but it does not compile for me:
override fun onCreateView(name: String?, context: Context?, attrs: AttributeSet?): View
{
var view = super.onCreateView(name, context, attrs)
my_btn.setOnClickListener( handleButtonClick )
return view
}
private val handleButtonClick = View.OnClickListener
{
view->
Log.d("my_tag", "click!")
}
What is wrong with the above, and how can I define an OnClickListener
as a named property on my Activity
class?
Kotlin Android – Set OnClickListener for Button Kotlin setOnClickListener for Button Android Button widget is a UI element generally used to receive user actions as input. You can click on a Button, long press, etc.
binding.button.setOnClickListener { Log.d ("TAG", "Example") } Best for achieve click listener in Kotlin (Mean Without findview by id you can click or intalize the textview, button, spinner etc) Then Sync the project.
First you have to get the reference to the View (say Button, TextView, etc.) and set an OnClickListener to the reference using setOnClickListener () method
{ Build and Run the Android Application. You would see the Android screen as shown in the following screenshot. Button.setOnClickListener () will be triggered and the code in this setOnClickListener {} block will run.
Indenting correctly fix the issue.
private val handleButtonClick = View.OnClickListener { view->
Log.d("my_tag", "click!")
}
as mentioned by others, as the view
param is the single one and is ignored, you can get rid of it.
if you want using an object:
val handleButtonClick = object : View.OnClickListener {
override fun onClick(view: View) {
Log.d("my_tag", "click!")
}
}
Edit : As mentioned by @Mango, this is a limitation stated in the grammar definition.
If you don't want lambda notations then this might work for you:
val onClickListener = object : View.OnClickListener {
override fun onClick(view: View) {
//ToDo: Implement whatever method you need
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With