How to pass a function as a parameter to another function in android?

So, how to pass a function as a parameter to another function, for example, I want to pass this function:

public void testFunkcija(){ Sesija.forceNalog(reg.getText().toString(), num); } 

in that:

  public static void dialogUpozorenjaTest(String poruka, Context context, int ikona, final Method func){ AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( context); alertDialogBuilder.setTitle("Stanje..."); alertDialogBuilder .setMessage(poruka) .setIcon(ikona) .setCancelable(true) .setPositiveButton("OK",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { //here } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } 
+7
source share
4 answers

You can use Runnable to port your method:

 Runnable r = new Runnable() { public void run() { Sesija.forceNalog(reg.getText().toString(), num); } } 

Then pass it to your method and call r.run(); where you need it:

 public static void dialogUpozorenjaTest(..., final Runnable func){ //..... .setPositiveButton("OK",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { func.run(); } }); } 
+15
source

Well, since there are no dellegates in Java (oh, C #, I miss you so much), the way you can do this is to create a class that implements an interface, maybe runnable or some kind of user interface, and what do you You can name your method through the interface.

+3
source

Functions cannot be passed directly. You can use the interface implementation as a callback mechanism to make a call.

Interface:

 public interface MyInterface { public void testFunkcija(); } 

Implementation:

 public class MyInterfaceImpl implements MyInterface public void testFunkcija(){ Sesija.forceNalog(reg.getText().toString(), num); } } 

and pass it an instance of MyInterfaceImpl , if required:

 public static void dialogUpozorenjaTest(MyInterface myInterface, ...) myInterface.testFunkcija(); ... 
+2
source

The easiest way is to use runnable see how

 //this function can take function as parameter private void doSomethingOrRegisterIfNotLoggedIn(Runnable r) { if (isUserLoggedIn()) r.run(); else new ViewDialog().showDialog(MainActivity.this, "You not Logged in, please log in or Register"); } 

Now let's see how I can pass any function to it (I will not use a lambda expression)

 Runnable r = new Runnable() { @Override public void run() { startActivity(new Intent(MainActivity.this, AddNewPostActivity.class)); } }; doSomethingOrRegisterIfNotLoggedIn(r); 

pass another function

 Runnable r = new Runnable() { @Override public void run() { if(!this.getClass().equals(MyProfileActivity.class)) { MyProfileActivity.startUserProfileFromLocation( MainActivity.this); overridePendingTransition(0, 0); } } }; doSomethingOrRegisterIfNotLoggedIn(r); 

here it is. happy big thinking ...

0
source

All Articles