-2

I am very new to Android Studio, and I have been looking at the official tutorial and found out this code:

public class MainActivity extends AppCompatActivity {
    public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user taps the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.editText);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

However, I don't see how that sendMessage() method is linked to the button we made in the tutorial. Which line mentions that this method corresponds to the button, which has a name button_send and a value of Send?

Pritt Balagopal
  • 1,476
  • 2
  • 18
  • 32
  • Possible duplicate of [How to handle button clicks using the XML onClick within Fragments](https://stackoverflow.com/questions/6091194/how-to-handle-button-clicks-using-the-xml-onclick-within-fragments) – Chisko May 20 '18 at 07:06

2 Answers2

3

In your layout file android:onClick="sendMessage" attribute should be there on which you want to call this function whenever tapped.

You don't need to link button to this method by yourself, android:onClick attribute does it for you. If you want to link that button to this function by yourself then you will have to give an id to that button using android:id="@+id/button_send" and then link in this way:

Button send = (Button) findViewById(R.id.button_send);
send.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
           sendMessage(v);
     }
});
Ghulam Moinul Quadir
  • 1,638
  • 1
  • 12
  • 17
1

In XML add this attribute "android:onClick="${methodName}" in Button element.

OR:

You can create button object and refference to UI.

public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Refference UI
    Button button = findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            sendMessage(view);
        }
    });

}

/** Called when the user taps the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.editText);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

}

Goffity
  • 142
  • 6