Java – Android – how to avoid duplicate code between activities

This is a general problem, but I will give you a specific example

I have many activities in the app. In all activities, there is a Facebook button. When you click this button, it will take you to a specific Facebook page. I want the button to behave exactly the same on each page

Now, in each activity, I create an onclicklistener () for the Facebook button, make the intention and start the activity. Each activity has the same code

What is the best way to write this code once and include it in multiple activities? Does it contain other. Java files anyway?

I know a solution that can be used is to create a basic customactivity class that extends the activity, and then let all activities extend the customactivity. Then put my onclicklistener () code in the customactivity. I'm a novice in Java, but I'm not sure this is the best way. Some of my activities have extended other custom activity classes as is, So things that expand more things may become a little chaotic, I don't know

UPDATE

Play the devil's advocate: let me say that I chose the inheritance route and created some customactivities that I want my activity to extend. Customactivity will contain a pile of common code that I need for all activities, Including but not limited to the Facebook button function. What happens when there is an activity and I need to use the common code in customactivity, but there is no Facebook button in that specific activity?

resolvent:

A common base class may be the best way. (if some of your activities extend activity and some extend activity subclasses (such as listactivity), it won't work well

Another way is to create a separate class to implement the logic of the click listener. This does not eliminate all duplicate code - each activity still needs to instantiate and register a listener - but you only need to write the logic once in the listener class

In any alternative, you can consider assigning the Android: onclick attribute to the button, so you don't need to register a click listener; You only need to implement the target method in each activity. This is particularly useful for base class methods

UPDATE

Suppose you go to the inheritance route and you want an activity without Facebook buttons. If you use Android: onclick technology, you don't have to perform any different operations in the code - because no button will call your onclick method, which will just sit there and do nothing. If you want to install onclicklistener in the code, Then you only need to test whether the button exists before registering the listener (that is, findviewbyid() does not return null)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>