Blog Tutorial Android Bagi Pemula

Thursday, December 17, 2020

Contoh Sederhana Dalam Menerapkan Fragment

Sebuah Fragment mewakili bagian yang dapat digunakan kembali dari antarmuka aplikasi. Fragment mendefinisikan dan mengelola tata letaknya sendiri, memiliki siklus prosesnya sendiri, dan dapat menangani peristiwa masukannya sendiri. Fragment tidak dapat hidup sendiri melainkan harus dihosting oleh aktivitas atau fragment lain. Hierarki tampilan fragment menjadi bagian dari, atau dilampirkan ke hierarki tampilan host.

Dalam tutorial ini akan dicontohkan penerapannya secara sederhana. Kita akan memiliki 4 Fragment dalam sebuah activity. Disini kita memiliki komponen atau view yang sama pada setiap layout fragment, sehingga kita tidak perlu membuat layout untuk masing-masing fragment, cukup satu saja.



Tentunya mari memulai dengan membuat sebuah project baru, dalam contoh ini kita menggunakan tema NoActionBar. Pada activity_main.xml, akan terdapat sebuah tombol yang berupa ImageView yang nantinya akan menampilkan PopUpMenu untuk navigasi antar fragment.



activity_main.xml :
<?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">

<LinearLayout
android:id="@+id/layoutHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/teal_700"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="10dp">

<TextView
android:id="@+id/textTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:layout_weight="1"
android:fontFamily="serif"
android:text="Android Fragments"
android:textColor="@color/white"
android:textSize="25sp" />

<ImageView
android:id="@+id/imageMenu"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="?selectableItemBackground"
android:contentDescription="@string/app_name"
android:src="@drawable/ic_menu"
app:tint="@color/white" />

</LinearLayout>

<FrameLayout
android:id="@+id/layoutFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</LinearLayout>


Pada layout diatas, kita memiliki sebuah Framelayout dengan id nya layoutFragment. Framelayout tersebut nantinya yang akan digantikan oleh fragment. Saat kita bernavigasi ke fragment 1, maka layout fragment 1 akan menggantikan Framelayout tersebut, begitupun untuk ketiga fragment lainnya.

Baik, sekarang kita persiapkan sebuah layout untuk ke-empat fragment tersebut. Disini kita buat dengan nama fragment_layout.xml, yang mana berisi 3 buah komponen view : TextView, ImageView, dan Button. Seperti yang sudah dikatakan diatas, karena kita memiliki view yang sama pada semua fragment sehingga kita tidak perlu membuat layout baru untuk setiap fragment, cukup satu untuk semua.

Namun seandainya kita akan memiliki view yang berbeda atau view dengan jumlah yang berbeda pada setiap fragment, tentunya kita perlu membuat layout nya berbeda-beda juga, atau bisa saja dengan layout yang sama namun menambahkan view secara terprogram melalui file java class dari fragment. Tentunya akan lebih sedikit merepotkan daripada membuat layout berbeda.

fragment_layout.xml :
<?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:gravity="center"
android:orientation="vertical"
android:padding="20dp">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:fontFamily="serif"
android:gravity="center"
android:text="Contoh Fragment"
android:textColor="@color/white"
android:textSize="25sp" />

<ImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginBottom="20dp"
android:contentDescription="@string/app_name" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-black"
android:text="Button Click"
android:textColor="@color/black"
android:textSize="20sp" />

</LinearLayout>


Selanjutnya kita membuat 4 file java class yang memperluas (extends) kelas Fragment. Disini kita buat dengan nama : Fragment1, Fragment2, Fragment3, dan Fragment4. Pada sebuah activity kita menggunakan argumen setContentView untuk menautkan konteks dengan layout, namum pada fragment kita menggunakan object View dengan LayoutInflater untuk menautkan ke layout, sama seperti kelas adapter ataupun kelas lainnya jika ingin menginflate layout.

Untuk keempat Fragment diatas isi kodingannya sama, disini kita hanya merubah nilai dari ketiga komponen view nya. Berikut ke-empat Fragment tersebut :

Fragment1 :
package com.gwnbs.contohfragment;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment1 extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);

TextView textView = view.findViewById(R.id.textView);
Button button = view.findViewById(R.id.button);
ImageView imageView = view.findViewById(R.id.imageView);

imageView.setImageResource(R.drawable.ic_1);
textView.setText("Ini adalah fragment 1");
button.setText("Click 1");

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(requireActivity(), "You're on Fragment 1", Toast.LENGTH_SHORT).show();
}
});

return view;
}
}

Fragment2 :
package com.gwnbs.contohfragment;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment2 extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);

TextView textView = view.findViewById(R.id.textView);
Button button = view.findViewById(R.id.button);
ImageView imageView = view.findViewById(R.id.imageView);

imageView.setImageResource(R.drawable.ic_2);
textView.setText("Ini adalah fragment 2");
button.setText("Click 2");

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(requireActivity(), "You're on Fragment 2", Toast.LENGTH_SHORT).show();
}
});

return view;
}
}

Fragment3 :
package com.gwnbs.contohfragment;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment3 extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);

TextView textView = view.findViewById(R.id.textView);
Button button = view.findViewById(R.id.button);
ImageView imageView = view.findViewById(R.id.imageView);

imageView.setImageResource(R.drawable.ic_3);
textView.setText("Ini adalah fragment 3");
button.setText("Click 3");

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(requireActivity(), "You're on Fragment 3", Toast.LENGTH_SHORT).show();
}
});

return view;
}
}

Fragment4 :
package com.gwnbs.contohfragment;

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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment4 extends Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);

TextView textView = view.findViewById(R.id.textView);
Button button = view.findViewById(R.id.button);
ImageView imageView = view.findViewById(R.id.imageView);

imageView.setImageResource(R.drawable.ic_4);
textView.setText("Ini adalah fragment 4");
button.setText("Click 4");

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(requireActivity(), "You're on Fragment 4", Toast.LENGTH_SHORT).show();
}
});

return view;
}
}


Selanjutnya kita membuat file resource menu, pada contoh ini yaitu menu_fragment.xml, untuk di inflate nantinya menggunakan PopUpMenu, yang berisi 4 item untuk bernavigasi antar fragment. Jika Anda belum tahu cara membuat resource menu, caranya klik kanan pada folder res > New > Android Resource File, kemudian pada resource type pilih menu. 

menu_fragment.xml :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item
android:id="@+id/menuFragment1"
android:title="Fragment 1"/>

<item
android:id="@+id/menuFragment2"
android:title="Fragment 2"/>

<item
android:id="@+id/menuFragment3"
android:title="Fragment 3"/>

<item
android:id="@+id/menuFragment4"
android:title="Fragment 4"/>

</menu>


Terakhir di MainActivity.java, pertama-tama kita buat sebuah metode private untuk berganti dari satu fragment ke fragment lainnya. Di dalam metode ini kita berikan 2 argumen yaitu Fragment dan String. Saat berganti fragment, disini kita juga merubah nilai string dari TextView pada actionBar, sehingga kita menggunakan argumen String supaya mudah. Kelas yang diperlukan untuk dapat berganti antar fragment yaitu FragmentManager dan FragmentTransaction.

Kemudian didalam onCreate kita menentukan metode klik listener untuk tombol yang ada di actionBar, yang mana didalam metode klik tersebut kita memanggil PopUpMenu, lalu menentukan kondisi berdasarkan id dari item PopUpMenu tersebut. Di setiap kondisi kita memanggil metode private yang sudah dibuat sebelumnya dengan Fragment (Fragment1, Fragment2, Fragment3, dan Fragment4) dan nilai String yang berbeda.


MainActivity.java :
package com.gwnbs.contohfragment;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.PopupMenu;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private TextView textTitle;

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

textTitle = findViewById(R.id.textTitle);

findViewById(R.id.imageMenu).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, view);
popupMenu.inflate(R.menu.menu_fragment);
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
int id = menuItem.getItemId();
if (id == R.id.menuFragment1) {
replaceFragment(new Fragment1(), "Fragment 1");
} else if (id == R.id.menuFragment2) {
replaceFragment(new Fragment2(), "Fragment 2");
} else if (id == R.id.menuFragment3) {
replaceFragment(new Fragment3(), "Fragment 3");
} else {
replaceFragment(new Fragment4(), "Fragment 4");
}
return true;
}
});
popupMenu.show();
}
});
}

private void replaceFragment(Fragment fragment, String title) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.layoutFragment, fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();

textTitle.setText(title);
}
}


Untuk gambar-gambar yang ada dalam project contoh ini, semua dibuat melalui Vector Asset.

Baik, sekian untuk tutorial ini. Terimakasih atas waktu dan kunjungannya, jika ada kekurangan dan kesalahan mohon dimaafkan, jika ada yang ingin disampaikan silahkan diposting dikomentar.
Share:

0 comments:

Post a Comment

Hubungi Saya

Name

Email *

Message *

Terlaris 30 Hari Terakhir