Same button for multiple actions

right I have a login button located exactly in the same place in every action, and I have 20 actions at the moment, but will grow much more soon, and I really don't want to copy and paste the same code for each actions, so I'm looking for a simple and effective solution to handle the onClick event, which will work globally throughout the application.

For example, if user A clicks on the enter button for action 1 and signs up, he will show that he has entered into action 2 and 3, etc. until they log out of the system.

The login button has the same identifiers throughout the application, which is "@ + id / signIn"

Would it be easier to name one function at the beginning of each action? I thought it would not be any efficient use of computing power, etc.?

Any suggestions and / or recommendations would be highly appreciated. Thanks:)

+6
source share
2 answers

You cannot avoid the realization of this listener in all your actions in any case. But you can do it in a slightly more organized way:

You can write your own header layout for your application ( /res/layout/header.xml ), in which you have an β€œLogin” button with a set for listening to clicks (pointing to the onSignInClicked method):

 android:onClick="onSignInClicked" 

Then you include this header in each action layout:

 <include android:id="@+id/header" layout="@layout/header" /> 

You can also create an interface that contains the declaration of the onSignInClicked method, and with all your actions that implement this interface, you force them to define the body of the onSignInClicked method.

What you are actually doing there can also be

  • static method inside a global accessible class, or
  • A well parameterized method inside your Application extension class.

therefore, in all your actions this method can be:

 public static void onSignInClicked(View view) { // static method with call with reference to the current activity SignInHelper.doSignIn(this); } 

or

 public static void onSignInClicked(View view) { // global method in your `Application` extension // with reference to the current activity ((MyApplication)getApplicationContext()).doSignIn(this); } 

If you choose the second method, be sure to update your androidManifes.xml by setting the name attribute of your Application tag:

 <application android:name=".MyApplication" [...] 
+8
source

You can create a button as a custom view.

0
source

Source: https://habr.com/ru/post/887050/


All Articles