Simple Android App to understand Activity Lifecycle
This code is an example of a simple Android app that demonstrates the Activity Lifecycle using Toast Messages.
The app contains a layout with a button, two text views, and a text field.
The onCreate()
method initializes the button, text views, and text field. The setOnClickListener()
method is used to set an event listener on the button that listens for click events.
When the button is clicked, a Toast message is displayed with the text entered in the text field, and the text is also displayed in the second text view.
The app also includes five other methods that demonstrate the Activity Lifecycle: onStart()
, onResume()
, onPause()
, onStop()
, and onRestart()
.
Each method displays a Toast message when the corresponding lifecycle event occurs.
Finally, the onDestroy()
method displays a Toast message when the activity is destroyed.
This code can be used as a starting point for building more complex Android apps that require event handling and interaction with the Activity Lifecycle.
private Button button;
private TextView text;
private TextView textView;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=findViewById(R.id.button);
text=findViewById(R.id.text1);
textView=findViewById(R.id.textView3);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String nameStr;
nameStr=text.getText().toString();
Toast.makeText(MainActivity.this, nameStr, Toast.LENGTH_SHORT).show();
textView.setText(nameStr);
}
});
}
@Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "On Start", Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "On Resume", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "On Pause", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "On Stop", Toast.LENGTH_SHORT).show();
}
@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(this, "On Restart", Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "On Destroy", Toast.LENGTH_SHORT).show();
}
}
Subscribe to my newsletter
Read articles from Arzath Areeff directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Arzath Areeff
Arzath Areeff
I co-founded digizen.lk to promote online safety and critical thinking. Currently, I’m developing an AI app to fight misinformation. As Founder and CEO of ideaGeek.net, I help turn startup dreams into reality, and I share tech insights and travel stories on my YouTube channels, TechNomad and Rz Omar.