How to Implement onClick Button Method In Android Applications.
In the previous lesson, we learned how to create a simple user interface in Android.Today lesson is all about implementing onClick Button method.
Implementing onClick Method
I will use onClick method to start another Activity.I will also go ahead and pass variables from this activity to the next activity.
1.First we need to define the method in activity layout xml file.
[
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"/> <!--When the button is clicked,sendMessage method will be executed.-->
]
2.Implement sendMessage method in the main Activity
[
import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /*Implementing sendMessage method*/ public void sendMessage(View view) { EditText message= (EditText)findViewById(R.id.enter_message); String text=message.getText().toString(); Intent intent=new Intent(this,DisplayActivity.class); intent.putExtra(EXTRA_MESSAGE,text); startActivity(intent); } }
]
3.Write code for DisplayActivity that will be started once the button is clicked.
[
import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import org.w3c.dom.Text; public class DisplayActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display); Intent intent=getIntent(); String message=intent.getStringExtra(MainActivity.EXTRA_MESSAGE); TextView view=new TextView(this); view.setTextSize(30); view.setText(message); ViewGroup layout=(ViewGroup)findViewById(R.id.activity_display); layout.addView(view); } }