ViewPager2 와 Fragments 를 이용한 탭메뉴 (AndroidX)

프로그래밍/Android (Java)|2020. 11. 26. 12:45
반응형

[출처]  http://www.tutorialsface.com/2020/07/android-tablayout-example-using-viewpager2-and-fragments-with-latest-android-api-androidx/


In this tutorial we are going to create 3 Tabs .Every tab have its own Fragment to control over screen. Also user can swipe between 3 tabs.

we are using AndroidX support Library , ViewPager2 and 3 different fragment & 3 different xml for layouts. And TabLayout for Tabs.

Layout Demonstration :

  • Checkout the following pic which explains the complete overview of layout architecture. Basically we are using ViewPager as main layout and for individual pager views we use Fragments. The tabs are part of Action Bar.

STEP 1: CREATING PROJECT

  • Let’s start with creating new project in android studio with package name com.example.manualSliding and class name MainActivity.java and its layout name is activity_main.xml.

STEP 2: ADDING DEPENDENCIES

  • open file Gradle Scripts/build.gradle(Module: app)
  • under dependencies{ } add this:
dependencies {
   
    //this is for ViewPager
    implementation "androidx.viewpager2:viewpager2:1.0.0"
    
    //this is for TabLayout
    implementation 'com.google.android.material:material:1.2.0-alpha01'

}
  • under compileOptions{} add this:
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

STEP 3: EDIT app/res/values/colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#0698bc</color>
<color name="colorPrimaryDark">#067d9b</color>
<color name="colorAccent">#FF4081</color>
<color name="frg1Color">#FEBE29</color>
<color name="frg2Color">#3395FF</color>
<color name="frg3Color">#F6437B</color>
<color name="txtBGColor">#9FA8DA</color>
<color name="white">#FFFFFF</color>
</resources>

STEP 4: EDIT app/res/values/styles.xml : we using this theme because TabLayout component works in this theme.

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

</resources>

STEP 6: CREATING LAYOUT FOR EACH FRAGMENT :

  • create new xml layout file under app/res/layout/first_frag.xml and add the below code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/frg1Color">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="356dp"
android:text="sample text 1"
android:textSize="25dp"
android:textStyle="bold"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • create new xml layout file under app/res/layout/second_frag.xml and add the below code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/frg2Color">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="356dp"
android:text="sample text 2"
android:textSize="25dp"
android:textStyle="bold"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
  • create new xml layout file under app/res/layout/third_frag.xml and add the below code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/cLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/frg3Color">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="356dp"
android:textSize="25dp"
android:textStyle="bold"
android:text="sample text 3"
android:textColor="@color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

STEP 7: Create FRAGMENT CLASS for each view layout:

  • create new java class under app/java/com.example.manualSliding/FirstFragment.java
package com.example.manualsliding;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

public class FirstFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);

TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setText(getArguments().getString("msg"));
return v;
}

public static FirstFragment newInstance(String text) {

FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);

f.setArguments(b);

return f;
}
}
  • create new java class under app/java/com.example.manualSliding/SecondFragment.java
package com.example.manualsliding;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

public class SecondFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);

TextView tv = (TextView) v.findViewById(R.id.textView1);
tv.setText(getArguments().getString("msg"));

return v;
}

public static SecondFragment newInstance(String text) {

SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);

f.setArguments(b);

return f;
}
}
  • create new java class under app/java/com.example.manualSliding/ThirdFragment.java
package com.example.manualsliding;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

public class ThirdFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.third_frag, container, false);

        TextView tv = (TextView) v.findViewById(R.id.textView1);
        tv.setText(getArguments().getString("msg"));

        return v;
    }

    public static ThirdFragment newInstance(String text) {

        ThirdFragment  f = new ThirdFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }
}

STEP 8: app/res/layout/activity_main.xml : here we are creating TabLayout and ViewPager2.

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

<com.google.android.material.tabs.TabLayout
android:id="@+id/tab_layout"
style="@style/Widget.MaterialComponents.TabLayout.Colored"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<androidx.viewpager2.widget.ViewPager2
android:id="@+id/mypager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />

</LinearLayout>

STEP 8: app/java/com.example.manualSliding/MainActivity.java

  • Here we use FragmentStateAdapter class for creating fragment and then we will assign it into Viewpager2.
  • create Strings array of tabs titles.
    • private String[] titles = new String[]{“Tab1”, “Tab2”, “Tab3”};
  • Inflating tab layout
    • TabLayout tabLayout =( TabLayout) findViewById(R.id.tab_layout);
  • Displaying tabs
    • new TabLayoutMediator(tabLayout, viewPager,(tab, position) -> tab.setText(titles[position])).attach();
  • complete code of MainActivity.java
package com.example.manualsliding;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class MainActivity extends AppCompatActivity {
private static final int NUM_PAGES = 3;
//The pager widget, which handles animation and allows swiping horizontally to access previous and next wizard steps.
 public static ViewPager2 viewPager;
// The pager adapter, which provides the pages to the view pager widget.
 private FragmentStateAdapter pagerAdapter;
// Arrey of strings FOR TABS TITLES
 private String[] titles = new String[]{"Tab1", "Tab2", "Tab3"};
// tab titles
 @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = findViewById(R.id.mypager);
pagerAdapter = new MyPagerAdapter(this);
viewPager.setAdapter(pagerAdapter);
//inflating tab layout
 TabLayout tabLayout =( TabLayout) findViewById(R.id.tab_layout);
//displaying tabs
 new TabLayoutMediator(tabLayout, viewPager,(tab, position) -> tab.setText(titles[position])).attach();
}

private class MyPagerAdapter extends FragmentStateAdapter {

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


@Override
public Fragment createFragment(int pos) {
switch (pos) {
case 0: {
return FirstFragment.newInstance("fragment 1");
}
case 1: {

return SecondFragment.newInstance("fragment 2");
}
case 2: {
return ThirdFragment.newInstance("fragment 3");
}
default:
return FirstFragment.newInstance("fragment 1, Default");
}
}

@Override
public int getItemCount() {
return NUM_PAGES;
}
}


@Override
public void onBackPressed() {
if (viewPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
 // Back button. This calls finish() on this activity and pops the back stack.d
 super.onBackPressed();
} else {
// Otherwise, select the previous step.
 viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}

}


[출처]  http://www.tutorialsface.com/2020/07/android-tablayout-example-using-viewpager2-and-fragments-with-latest-android-api-androidx/


반응형

댓글()