What’s is Activity in Android
Ans : An Activity in Android represents a single screen with a user interface, much like a window or a frame in other programming environments. It acts as an entry point for users to interact with your application. An Android app is typically composed of multiple activities that work together to create a cohesive user experience. Each activity is independent but can communicate with other activities via intents.
An activity is crucial because it handles the creation of the app’s UI (User Interface) and responds to user actions, such as clicking a button or entering text. The `Activity` class in Android provides a set of lifecycle methods that manage the state of an activity, including `onCreate()`, `onStart()`, `onResume()`, `onPause()`, `onStop()`, and `onDestroy()`. These methods allow developers to manage resources and handle user interactions appropriately.
Table of Contents
Java Example: A Basic Android Activity
Below is an example of a simple Android activity that displays a message when a button is clicked in Android
MainActivity.java
```java
package com.example.simpleactivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the button by its ID
Button myButton = findViewById(R.id.my_button);
// Set an OnClickListener on the button
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Display a Toast message
Toast.makeText(MainActivity.this, "Button Clicked!", Toast.LENGTH_SHORT).show();
}
});
}
}
activity_main.xml
```xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_centerInParent="true"/>
</RelativeLayout>
```
Explanation of the Code Activity in Android:
- MainActivity.java: The main activity that manages the UI.
- setContentView(): Sets the layout for the activity using the XML layout file.
- findViewById(): Finds the button in the layout using its ID.
- OnClickListener: Listens for click events on the button. When the button is clicked, a toast message is displayed.Activity in Android
- activity_main.xml: The layout file that defines the UI of the activity, containing a single button centered on the screen.
This example demonstrates how an activity manages the UI and responds to user actions in Android an Android app.