Pass value to a java function

Asked

Viewed 902 times

0

Hello! in Javascript to pass a value to the function I do:

<button onclick="myFunction('valor')">Click me</button>

and crawl like this:

function myFunction(a){alert(a);}

and in java on android, as I do?

3 answers

3


Represents a widget button. Buttons can be pressed or clicked by the user to perform an action. A typical use of an Activity button would be the following

public class MyActivity extends Activity {
     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);

         setContentView(R.layout.content_layout_id);

         final Button button = (Button) findViewById(R.id.button_id);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // Faça algo aqui quando clicar no botão.
             }
         });
     }
 }

However, instead of applying Onclicklistener to the button in your Activity, you can assign a method to the button in the XML layout, using the attribute android:onClick. For example:

 <Button
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="@string/self_destruct"
     android:onClick="selfDestruct" />

Now, when a user clicks on the button, the Android system calls the activity method selfDestruct(View). For this to work, the method must be public and accept a View as its only parameter. For example:

 public void selfDestruct(View view) {
     // Faça algo aqui quando clicar no botão.
 }

To View passed to the method is a reference to the widget that was clicked.


Reference here: Documentación Oficial

0

 <Button
     android:layout_height="wrap_content"
     android:layout_width="wrap_content"
     android:text="@string/self_destruct"
     android:onClick="selfDestruct" />

taken from the above answer, it is quite simple.

  • 3

    I don’t understand why this answer... if it’s already in the other answer why repeat it so often!

0

It would be better if you put what you need to facilitate the help... but it would be something +- like this...

public static int soma(int a, int b)  
{  
    int c = a + b;  
    return c;  
} 
  • thanks in advance, and how do I create the button in xml layout

Browser other questions tagged

You are not signed in. Login or sign up in order to post.