2015-06-05 72 views
1

我想傳遞一個方法(SaveClound)作爲參數(AlertDialog參數),所以我可以通過該參數(在actionButtons方法)使用型動物的方法。如何在Android中將方法作爲參數傳遞?

public void actionButtons(){ 
    buttonVoltar.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      alertDialog(saveClound()); 
      // see? I want to call the a method through this parameter 
     } 
    }); 
} 

public void alertDialog(Method methodName) { 
    AlertDialog.Builder builderaction = new AlertDialog.Builder(this); 
    builderaction.setTitle("Atenção!"); 
    builderaction.setMessage("Você tem certeza que deseja sair?"); 

    builderaction.setPositiveButton("Yes",new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        // i want to call here the paramater i'm passing on this method (methodName) 
        // so i can call any methods i want right here 
       } 
      }); 
    builderaction.setNegativeButton("No",new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.dismiss(); 
       } 
      }); 
    AlertDialog alert = builderaction.create(); 
    alert.setIcon(R.drawable.ic_stop); 
    alert.show(); 
} 


public void saveClound(){ 
    Toast.makeText(getApplicationContext(), "ABC", Toast.LENGTH_SHORT).show(); 
} 
+1

如果你試圖傳遞的方法作爲參數做到這一點,就不可能本身在Java中。有些方法可以通過Interfaces來完成。檢查這個SO問題。 http://stackoverflow.com/questions/2186931/java-pass-method-as-parameter – JDenais

+0

我看到了,但我無法理解它..:/ –

+0

看看我的[回覆](https:// stackoverflow.com的.com /問題/ 16800711 /傳遞功能作爲一種參數合的java/46933426#46933426) –

回答

1

你可以通過一個可運行的方法例如

public void actionButtons(){ 
    buttonVoltar.setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 

      Runnable runnable = new Runnable() { 
       @Override 
       public void run() { 
        saveClound(); 
       } 
      }; 

      alertDialog(runnable); 
     } 
    }); 
} 

public void alertDialog(Runnable runnable) { 
    AlertDialog.Builder builderaction = new AlertDialog.Builder(this); 
    builderaction.setTitle("Atenção!"); 
    builderaction.setMessage("Você tem certeza que deseja sair?"); 

    builderaction.setPositiveButton("Yes",new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
       // i want to call here the paramater i'm passing on this method (methodName) 
       // so i can call any methods i want right here 
       new Handler().post(runnable); 
      } 
     }); 
    builderaction.setNegativeButton("No",new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.dismiss(); 
      } 
     }); 
    AlertDialog alert = builderaction.create(); 
    alert.setIcon(R.drawable.ic_stop); 
    alert.show(); 
} 

public void saveClound(){ 
    Toast.makeText(getActivity(), "ABC", Toast.LENGTH_SHORT).show(); 
} 
相關問題