Switching to OnClickListeners, 47/100 Days of code
In my latest update to the Travel app, I refactored my code with onClickListeners. This makes it easier to maintain later down the line.
I updated my Travel app to use onClickListeners to start Activities when needed. You can find the video on this at the bottom of the page and a link to the source code here.
To do this, I removed the android:onClick XML attribute from the TextViews in the activity_main.xml file. These attributes are used to invoke a method when the TextViews are clicked.
Next, I set ids for each TextView using the android:id XML attribute. Afterwards, I instantiated TextView objects in MainActivity.java using the findViewById method to reference the TextViews in the activity_main.xml file based on their ids.
Finally, I used the setOnClickListener() method to configure each TextView to create an Intent and start their respective Activities when clicked.
I removed the android:onClick XML attributes from the TextViews in order to keep all code related to user interactions in the MainActivity.java file. Assigning ids to the TextViews used for options allowed me to reference them using objects in MainActivity.java. Creating these objects lets the class configure how the TextViews behave by overriding methods from the View class.
Keeping code related to user interactions in one place makes it easier to maintain my code. I know where to look in the event something doesn’t work when users click the options. Now that the logic is only stored in the MainActivity.java file, I have optimized debugging proactively. It’s easier to find your keys when you always keep them in the same place.
Next, I will configure the List_Addresses.java file to display the list of addresses being used for this app. For more on this, watch the YouTube video below. For the source code click here.
Join the mailing list to see updates like this every week!
Coding Fanatic