Java Android App Development Course, Positioning with Relative Position – RelativeLayout

In Android app development, various layouts can be used, one of which is RelativeLayout.
RelativeLayout is a layout that allows child views to be positioned relative to each other.
Using this layout, each view can be arranged relative to other views on the screen, making it advantageous for composing complex UIs.

What is RelativeLayout?

RelativeLayout allows child views to be positioned in relation to the specified parent view.
In other words, users can define the position of each view in respect to the direction on the screen.
For example, it is possible to place one view to the right of another view or to align it in the center of the parent layout.

Main Attributes of RelativeLayout

When using RelativeLayout, the main attributes that can be applied to child views are as follows:

  • android:layout_alignParentTop: Aligns to the top of the parent
  • android:layout_alignParentBottom: Aligns to the bottom of the parent
  • android:layout_alignParentLeft: Aligns to the left of the parent
  • android:layout_alignParentRight: Aligns to the right of the parent
  • android:layout_centerInParent: Aligns in the center of the parent
  • android:layout_toLeftOf: Aligns to the left of the specified view
  • android:layout_toRightOf: Aligns to the right of the specified view
  • android:layout_above: Aligns above the specified view
  • android:layout_below: Aligns below the specified view

Advantages of RelativeLayout

Several advantages of using RelativeLayout include:

  • Flexible Layout Modification: It is easy to change the relative positions of existing views, making UI modifications convenient.
  • Ability to Compose Complex Layouts: You can easily create complex UIs compared to other layouts.
  • Performance Improvement: It can improve performance by reducing nested layouts.

Example of Using RelativeLayout

Now let’s learn how to use RelativeLayout through an example that includes views positioned relative to each other.
The example below shows how to arrange a TextView, Button, and ImageView using RelativeLayout.

Step 1: Project Setup

Create a new project in Android Studio,
and modify the provided activity_main.xml file.

Step 2: XML Layout Code

        
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/text_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Hello, World!"
                android:textSize="24sp"
                android:layout_centerInParent="true"/>

            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Click Me"
                android:layout_below="@id/text_view"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="16dp"/>

            <ImageView
                android:id="@+id/image_view"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:src="@drawable/ic_launcher_foreground"
                android:layout_above="@id/button"
                android:layout_centerHorizontal="true"
                android:layout_marginBottom="16dp"/>

        </RelativeLayout>
        
    

Step 3: Adding Actions to the Views

After setting up the XML layout, let’s implement actions for those views.
Open the MainActivity.java file and add the code below.

        
        package com.example.myapp;

        import androidx.appcompat.app.AppCompatActivity;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.TextView;

        public class MainActivity extends AppCompatActivity {

            private TextView textView;
            private Button button;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                textView = findViewById(R.id.text_view);
                button = findViewById(R.id.button);

                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        textView.setText("The button has been clicked!");
                    }
                });
            }
        }
        
    

Disadvantages of RelativeLayout

While RelativeLayout is very useful, it has some disadvantages.
Firstly, complex layouts can lead to performance degradation.
Additionally, there is a risk that multiple views may overlap or collide, which can make it visually difficult to see the order of views.

Comparing RelativeLayout with Other Layouts

RelativeLayout has its own strengths and weaknesses compared to other layouts such as LinearLayout and ConstraintLayout.
LinearLayout is suitable for arranging child views vertically or horizontally,
whereas ConstraintLayout offers more complex yet flexible layouts.
It is important to choose the appropriate layout according to the requirements of the user interface.

Conclusion

In this tutorial, we learned how to use RelativeLayout in Android to position views relatively.
RelativeLayout is characterized by its ability to easily set relationships with other views while constructing a UI,
making it suitable for various UI requirements.
Further, unleash your creativity in making your own app!

Java Android App Development Course, Obtaining User Location

User location information is a very important element in Android app development. To provide personalized services to users and enhance the functionality of our app, we need to understand the user’s current location. In this article, we will explain in detail how to obtain user location in Android apps using Java and provide related example code.

1. The Necessity of Acquiring User Location

Let’s explore why obtaining user location is important and what functionalities can be implemented through it. For example:

  • Location-Based Services: You can recommend nearby restaurants, cafes, etc., based on the user’s current location.
  • Navigation Feature: If the user inputs a starting point and a destination, the app can guide them along the optimal route.
  • Location History: You can record places the user has visited and analyze them based on this information.

2. Overview of Android Location Services

In Android, you can use the Location API of Google Play Services to easily obtain user location. This API helps determine the user’s location through information from GPS, Wi-Fi, cellular towers, and more.

3. Project Setup

First, you need to create a new project in Android Studio and add the necessary libraries.

3.1. Gradle File Setup

build.gradle (Module: app)
dependencies {
    implementation 'com.google.android.gms:play-services-location:21.0.1'
}

By adding the above Gradle dependency, you can use the location API through Google Play Services.

3.2. Update AndroidManifest.xml

You need to specify the permissions required to use location information in the AndroidManifest.xml file.

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.locationapp">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application ...>
        ...
    </application>
</manifest>

4. Requesting Location Permissions

To access the user’s location, you need to request location permissions. On Android 6.0 (API Level 23) and above, permissions must be requested at runtime. Here’s how to request permissions.

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, 
        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 
        LOCATION_PERMISSION_REQUEST_CODE);
}

5. Acquiring Location Data

Now that we have obtained permissions, we will write a class to fetch the user’s location. Below is the code to get the user’s location.

public class MainActivity extends AppCompatActivity {

    private FusedLocationProviderClient fusedLocationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        // Get latitude and longitude
        getLocation();
    }

    private void getLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && 
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        
        fusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener() {
                @Override
                public void onSuccess(Location location) {
                    // Successfully obtained location
                    if (location != null) {
                        double latitude = location.getLatitude();
                        double longitude = location.getLongitude();
                        Toast.makeText(MainActivity.this, "Latitude: " + latitude + ", Longitude: " + longitude, Toast.LENGTH_LONG).show();
                    }
                }
            });
    }
}

6. Receiving Location Updates

To receive real-time location updates as the user moves, you need to use the LocationRequest object to request location updates. Here’s how to set up location updates.

private void startLocationUpdates() {
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000); // Update every 10 seconds
    locationRequest.setFastestInterval(5000); // Fastest update interval 
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationCallback locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
                // Called whenever the location changes
                if (location != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    Toast.makeText(MainActivity.this, "Latitude: " + latitude + ", Longitude: " + longitude, Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
}

7. Stop Location Updates When App is Closed

Continuously tracking a user’s location can drain battery. Therefore, you must stop location updates when a user exits the app.

@Override
protected void onPause() {
    super.onPause();
    fusedLocationClient.removeLocationUpdates(locationCallback);
}

8. Additional Feature: Display Location on Map

Let’s add a feature to display the user’s location on a map. This can be implemented using the Google Maps API.

8.1. Integrating the Map

To use the Google Maps API, you need to generate an API key from Google Cloud Platform and add it to the AndroidManifest.xml.

<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="YOUR_API_KEY"/>

8.2. Adding Location Marker to the Map

private GoogleMap mMap;

@Override
protected void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // Code to display current location
    LatLng currentLocation = new LatLng(latitude, longitude);
    mMap.addMarker(new MarkerOptions().position(currentLocation).title("Current Location"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(currentLocation));
}

9. Conclusion and References

In this tutorial, we explored how to obtain user location in Android apps using Java. We covered requesting location permissions, acquiring location data, and methods for location updates. This will allow you to effectively utilize location information, an important component of Android app development.

9.1. References

Important: When handling location information, you must consider user privacy and provide clear explanations to users regarding the use of their location.

Java Android App Development Course, Understanding Broadcast Receivers

Hello! In this article, we will take a closer look at a specific topic that is important in Android app development: Broadcast Receivers. A Broadcast Receiver is a powerful component for receiving and processing various system events that occur in Android. Understanding and utilizing these components effectively will greatly help in creating well-functioning apps.

What is a Broadcast Receiver?

A Broadcast Receiver is a component that can receive various events occurring in the Android system. For example, it can receive events when the power is connected, network changes, or when the boot process is completed and perform appropriate actions. These events are transmitted in the form of “broadcasts” and can be received simultaneously by multiple apps.

Types of Broadcasts

  • Global Broadcast: A broadcast that can be received by all apps. For example, ACTION_BOOT_COMPLETED occurs when the Android system has booted.
  • App-Specific Broadcast: A broadcast that is only sent among the components of a specific app. These broadcasts are only valid within that app.

Examples of Using Broadcast Receivers

Broadcast Receivers are mainly used in situations such as:

  • Receiving system events (e.g., receiving a phone call, changing Wi-Fi status, etc.)
  • Processing app data (e.g., requesting updates from another app after a certain task is completed)
  • Changes in app state (e.g., sending notifications when a user logs out)

Implementing a Broadcast Receiver

Now let’s take a step-by-step look at how to implement a Broadcast Receiver. In this example, we will create a simple Broadcast Receiver that logs information whenever the battery status changes.

1. Create a Broadcast Receiver Class


package com.example.broadcastrreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.util.Log;

public class BatteryReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        float batteryPct = level / (float)scale * 100;

        Log.d("BatteryReceiver", "Battery level: " + batteryPct + "%");
    }
}

2. Registering the Receiver in AndroidManifest.xml

A Broadcast Receiver must be registered in the AndroidManifest.xml file so that the system can recognize it. To receive changes in battery status, configure it as follows.




    
        
        
            
                
            
        
    

3. Verify Receiver Functionality in the App

Once the above setup is complete, install and run the app. Now you can check the logcat to see the battery level output every time the battery level changes.

Advantages and Considerations of Broadcast Receivers

Broadcast Receivers have several advantages, but there are also some considerations to keep in mind while using them.

  • Advantages:
    • Easy to receive various system events
    • Centralizes resource and event handling of the app
  • Considerations:
    • Inherently asynchronous, which may lead to resource leak issues depending on the situation
    • Permissions must be correctly set for normal operation

Comparing Global and App-Specific Broadcasts

The main difference between global broadcasts and app-specific broadcasts lies in the receiving scope. Global broadcasts can be received by all apps, while app-specific broadcasts can only be received within a particular app. For example, you can implement an app-specific broadcast as follows.


Intent intent = new Intent("com.example.broadcastrreceiver.MY_NOTIFICATION");
sendBroadcast(intent);

Registering an App-Specific Broadcast Receiver



    
        
    

Conclusion

Broadcast Receivers play an important role as components within Android apps. Through them, system events can be effectively received and handled, allowing for more efficient management of app resources. This tutorial has covered the basic concepts, usage, and examples of Broadcast Receivers, and aims to provide a concrete understanding of how to receive various system events.

As you continue Android development, try to leverage Broadcast Receivers in more diverse situations. In the next tutorial, we will take a closer look at another Android component: Services.

References

Java Android App Development Course, How to Design Screens Using Views

In Android app development, the layout of the screen is a crucial element that significantly affects the user experience. In this course, we will deeply explore how to construct screens using views in Android app development with Java. We will examine the various types of views, their usage, the development of custom views, and the screen composition using XML layout files step by step.

1. What is a View in Android?

A View is the fundamental element that makes up the user interface of an Android application. All UI elements displayed on the screen, such as buttons, text, and images, are views. Android provides the View class and various subclasses that inherit from it to effectively handle these views.

1.1 Types of Views

There are various types of views in Android. Here are the most commonly used view classes:

  • TextView: A view that displays text.
  • EditText: A text box that can receive user input.
  • Button: A clickable button.
  • ImageView: A view that displays an image.
  • LinearLayout: A layout that arranges child views either vertically or horizontally.

2. XML Layout Files

The UI of Android apps is mainly defined in XML files. These XML files represent the view hierarchy and allow you to set properties for each view. To create an XML layout file, follow these steps.

2.1 Creating a Layout File

1. Locate the res/layout folder in the project.
2. Right-click and select New > Layout Resource File.
3. Enter the file name and click OK.

2.2 Structure of XML Layout

The basic structure of an XML layout file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello, World!" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me!" />

</LinearLayout>

The example above defines vertically arranged text and a button using LinearLayout. The layout_width and layout_height properties of each view set the size of the view.

3. Dynamically Creating Views in Java

While defining layouts through XML is good, sometimes it’s necessary to dynamically create views through Java code. Let’s look at how to dynamically create views in Java.

3.1 Creating Basic Views

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);

TextView textView = new TextView(this);
textView.setText("Hello, World!");

Button button = new Button(this);
button.setText("Click Me!");

layout.addView(textView);
layout.addView(button);

setContentView(layout);

In the code above, we created a LinearLayout, then created a TextView and a Button and added them to the layout. Finally, we display this layout on the screen using the setContentView method.

3.2 Event Handling

To handle events such as button clicks, you can set listeners. Here’s how to handle button click events:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(getApplicationContext(), "Button Clicked!", Toast.LENGTH_SHORT).show();
    }
});

4. Structuring Content with Layouts

Android applications increasingly demand more complex layouts beyond simple screen configurations. Let’s explore how to apply various combinations of layouts.

4.1 ConstraintLayout

ConstraintLayout allows you to define the relationships between components to easily create complex UIs. Here’s a basic usage example.

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Hello, World!"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

4.2 RecyclerView

When you need to display a lot of data, it’s advisable to use RecyclerView. It helps efficiently layout many items. Let’s also look at the basic usage of RecyclerView.

Creating a RecyclerView Adapter

public class MyAdapter extends RecyclerView.Adapter {
    private String[] mData;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView textView;
        public ViewHolder(View v) {
            super(v);
            textView = v.findViewById(R.id.textView);
        }
    }

    public MyAdapter(String[] data) {
        mData = data;
    }

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.text_view_item, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        holder.textView.setText(mData[position]);
    }

    @Override
    public int getItemCount() {
        return mData.length;
    }
}

The code above demonstrates how to create an adapter for RecyclerView. This adapter receives a data array and sets the data for each view.

5. Creating Custom Views

There are times when you need to create custom views to meet specific UI/UX requirements. The process for creating custom views is as follows.

5.1 Create a Custom View Class

public class MyCustomView extends View {
    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // Initialization work
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // Code to draw the view
    }
}

The code above shows the basic configuration of a custom view that inherits from the View class. The onDraw method can be used to perform direct drawing operations.

Conclusion

In this course, we explored how to compose screens using views in Android app development with Java. We covered various methods to effectively build the user interface of Android applications, from static composition using XML layout files to dynamic creation through Java code, as well as developing complex layouts and custom views.

Based on what you learned in this course, try applying various views and layouts that your app needs. Android app development is continuously evolving, and it is important to learn new technologies and methods in a timely manner. We will return with more in-depth topics in the future.

Java Android App Development Course, View Pager 2 – Screen Composition with Swipe

In Android application development, user experience is very important, and various UI components are needed to help users navigate the app naturally. Among them, the ViewPager provides an experience for users to swipe through multiple screens. In this post, we will learn how to configure swipeable screens using ViewPager2.

Overview of ViewPager

ViewPager is a UI component that allows users to navigate by swiping left and right through multiple pages. It helps users easily move to the desired page as they swipe the screen. ViewPager2 is an improved version of the existing ViewPager, providing better performance and flexibility based on RecyclerView.

Features of ViewPager2

  • RecyclerView Based: ViewPager2 integrates with RecyclerView to offer more features and optimizations.
  • Vertical and Horizontal Scroll: It supports horizontal scrolling by default, and vertical scrolling can be enabled through settings.
  • Fragment Support: ViewPager2 allows you to use fragments directly, making it easy to organize multiple screens.

Setting Up the Development Environment

To use ViewPager2, you need to create a new project using Android Studio and Gradle. Please follow the steps below.

  1. Open Android Studio and select File > New > New Project.
  2. Select Empty Activity and set the project name and package name.
  3. Add the ViewPager2 dependency to the Gradle file.

Adding Gradle Dependency

dependencies {
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
}

After adding the above dependency to the build.gradle (Module: app) file, sync the project.

Implementing ViewPager2

1. Configuring the Layout

First, add ViewPager2 to the activity_main.xml file as follows.

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

2. Creating the Adapter

Next, you need to create an adapter that manages the data for the ViewPager2. The adapter must inherit from RecyclerView.Adapter.

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MyPagerAdapter extends RecyclerView.Adapter {

    private String[] data;

    public MyPagerAdapter(String[] data) {
        this.data = data;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(android.R.layout.simple_list_item_1, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.textView.setText(data[position]);
    }

    @Override
    public int getItemCount() {
        return data.length;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        public ViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(android.R.id.text1);
        }
    }
}

3. Implementing MainActivity

Now, we will initialize the ViewPager2 in the main activity and connect it to the created adapter.

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

public class MainActivity extends AppCompatActivity {

    private ViewPager2 viewPager;
    private MyPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.viewPager);
        String[] data = {"Screen 1", "Screen 2", "Screen 3", "Screen 4"};
        adapter = new MyPagerAdapter(data);
        viewPager.setAdapter(adapter);
    }
}

Using Fragments with ViewPager2

Now, we will use fragments in ViewPager2 to create a more complex UI. Using fragments is useful for implementing various screens.

1. Creating Fragments

We will create new fragments to configure each screen.

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class ScreenSlidePageFragment extends Fragment {
    private static final String ARG_OBJECT = "object";

    public static ScreenSlidePageFragment create(int position) {
        ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_OBJECT, position);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(android.R.layout.simple_list_item_1, container, false);
        TextView textView = view.findViewById(android.R.id.text1);
        textView.setText("Fragment " + getArguments().getInt(ARG_OBJECT));
        return view;
    }
}

2. Modifying the Adapter

We will modify the adapter to use fragments.

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

public class ScreenSlidePagerAdapter extends FragmentStateAdapter {

    public ScreenSlidePagerAdapter(FragmentActivity fa) {
        super(fa);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return ScreenSlidePageFragment.create(position);
    }

    @Override
    public int getItemCount() {
        return 4; // Number of fragments
    }
}

3. Setting the Adapter in MainActivity

Finally, we will set the adapter in MainActivity.

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;

public class MainActivity extends AppCompatActivity {

    private ViewPager2 viewPager;
    private ScreenSlidePagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.viewPager);
        adapter = new ScreenSlidePagerAdapter(this);
        viewPager.setAdapter(adapter);
    }
}

Advantages and Use Cases of ViewPager2

  • Excellent User Experience: Provides smooth screen transitions and interactive UI, enhancing the naturalness of app navigation.
  • Variety of Screen Layouts: Almost any type of screen can be configured using fragments, making it easy to reuse and maintain.
  • ViewPager and Animation: ViewPager2 supports various animation effects, allowing for more attractive UI/UX.

Conclusion

In this post, we learned how to create swipeable screens for users using ViewPager2. We learned how to manage data using adapters and how to configure complex UIs using fragments. By leveraging these techniques, you can develop more attractive and user-friendly Android applications.

In future posts, we will cover a variety of topics related to Android development, so please stay tuned!