I am trying to set OnClickListener
on an Android
button in Kotlin file. Unlike java file, where I can declare button variable at the class level and initialize it in onCreate
method and assign ClickListener at the same time as:
Button inlineButton;
@Override
public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
inlineButton = findViewById(R.id.btn_inline);
inlineButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new NotificationToast(MainActivity.this, "Inline Button");
}
});
}
when I try to follow similar pattern I get an error with the following message:
I can only set the event handler only when I create a copy of button with following code:
var inlineButton : Button? = null;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
inlineButton = findViewById(R.id.btn_inline)
val inlineButtonCopy = inlineButton;
if (inlineButtonCopy != null) {
inlineButtonCopy.setOnClickListener({
NotificationToast(this,inlineButtonCopy.text.toString()).Show();
})
}
}
I was wondering if it is not possible to create only a single instance of Button on top level, initialize it in oncreate, and set event handler. If I can create only a single instance, I can use the event to change the property of the same button. Is it the default behavior or am I missing something.
Any clarification is highly appreciated.
In Kotlin you don't need to define the Id's
of the XML component.
you can directly access with the help of Id's
are already defined in your XML.
let suppose you defined the Button
Id in XML is btn_inline
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_inline.setOnClickListener({
NotificationToast(this,inlineButtonCopy.text.toString()).Show();
})
}
Also, make sure that something like this should be present there in the import
section.
import kotlinx.android.synthetic.main.activity_main.*
Just check at your end.