I’m creating my own Navigation Drawer in my Android app and I was wondering which is better practice.
I can either:
Add a tag in my layout.xml like this android:onClick="btnHome"
and then just add the method btnHome() into my .java file.
OR
Give an id to my element like this android:id="@+id/btnHome"
Give it an onClickListener findViewById(R.id.btnHome).setOnClickListener(this);
in my setContentView() or onCreate() method
and then implement the OnClickListener in my class
@Override public void onClick(View v) { switch (v.getId()) { case R.id.btnHome: // The 'Home' button in the navigation drawer //TODO: Make it go to home screen break; } }
I know both ways can produce the same result but I’m curious if there is any difference between them that I’m not aware of.
Advertisement
Answer
Using “setOnClickListener” is always recommended over “android:onClick”. You should create a separate “OnClickListener” for each button, unless all buttons do the same thing or share functionality, which in that case you can just create one “OnClickListener” and assign it to all buttons. Also use Kotlin and ViewBinding.