Universitas Kebudayaan Digital Makassar

Universitas Kebudayaan Digital Makassar (UKDMKS) memadukan inovasi teknologi digital dengan pelestarian budaya lokal. Bergabunglah untuk membangun masa depan berbasis budaya dan teknologi!

android studio

Cara Membuat Flexible Fragment di Satu Activity Aplikasi Android


Codelab Flexible Fragment di Satu Activity

Selanjutnya kita akan mencoba untuk membuat fragment baru yang fleksibel. Kencangkan sabukmu. Get ready and Go!

  1. Dengan cara yang sama seperti sebelumnya, buat fragment baru dengan nama CategoryFragment . Jangan lupa untuk uncheck pilihan untuk generate default methods dan callbacks

    201811131018548d6ba9e4c48831b7b87c32f0cfaaf708

  2. Pada fragment_category silakan kondisikan kode Anda menjadi seperti berikut:
  1. <LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
  2.     xmlns:tools=“http://schemas.android.com/tools”
  3.     android:layout_width=“match_parent”
  4.     android:layout_height=“match_parent”
  5.     android:orientation=“vertical”
  6.     android:padding=“16dp”>
  7.  
  8.     <TextView
  9.         android:layout_width=“match_parent”
  10.         android:layout_height=“wrap_content”
  11.         android:layout_marginBottom=“16dp”
  12.         android:text=“@string/this_category” />
  13.     <Button
  14.         android:id=“@+id/btn_detail_category”
  15.         android:layout_width=“match_parent”
  16.         android:layout_height=“wrap_content”
  17.         android:text=“@string/category_lifestyle” />
  18. </LinearLayout>

Selesai dengan layout xml, kini pada berkas CategoryFragment modifikasi kodenya menjadi sebagai berikut:


  1. class CategoryFragment : Fragment(), View.OnClickListener {

  2.  

  3. override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,

  4. savedInstanceState: Bundle?): View? {

  5. // Inflate the layout for this fragment

  6. return inflater.inflate(R.layout.fragment_category, container, false)

  7. }

  8.  

  9.     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

  10.         super.onViewCreated(view, savedInstanceState)

  11.         val btnDetailCategory:Button = view.findViewById(R.id.btn_detail_category)

  12.         btnDetailCategory.setOnClickListener(this)

  13.     }

  14.  

  15.     override fun onClick(v: View) {

  16.         if (v.id == R.id.btn_detail_category) {

  17.  

  18.         }

  19.     }

  20. }





  1. public class CategoryFragment extends Fragment implements View.OnClickListener {

  2.  

  3. public CategoryFragment() {

  4. }

  5.  

  6.  

  7. @Override

  8. public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,

  9. Bundle savedInstanceState) {

  10. // Inflate the layout for this fragment

  11. return inflater.inflate(R.layout.fragment_category, container, false);

  12. }

  13.    

  14.     @Override

  15.     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

  16.         super.onViewCreated(view, savedInstanceState);

  17.         Button btnDetailCategory = view.findViewById(R.id.btn_detail_category);

  18.         btnDetailCategory.setOnClickListener(this);

  19.     }


  20.     @Override

  21.     public void onClick(View v) {

  22.         if (v.getId() == R.id.btn_detail_category){


  23.         }

  24.     }

  25. }




  1. Sama seperti sebelumnya, kita siapkan onClick untuk modul berikutnya yaitu Mengirim Data Antar Fragment”.
  2. Sekarang kembali pada HomeFragment . Tambahkan baris berikut pada metode onClick()


  1. override fun onClick(v: View) {

  2. if (v.id == R.id.btn_category) {

  3. val mCategoryFragment = CategoryFragment()

  4. val mFragmentManager = fragmentManager

  5. mFragmentManager?.beginTransaction()?.apply {

  6. replace(R.id.frame_container, mCategoryFragment, CategoryFragment::class.java.simpleName)

  7. addToBackStack(null)

  8. commit()

  9. }

  10. }

  11. }





  1. @Override

  2. public void onClick(View v) {

  3. if (v.getId() == R.id.btn_category) {

  4. CategoryFragment mCategoryFragment = new CategoryFragment();

  5. FragmentManager mFragmentManager = getFragmentManager();

  6. if (mFragmentManager != null) {

  7. mFragmentManager

  8. .beginTransaction()

  9. .replace(R.id.frame_container, mCategoryFragment, CategoryFragment.class.getSimpleName())

  10. .addToBackStack(null)

  11. .commit();

  12. }

  13. }

  14. }



Sehingga kode dari HomeFragment menjadi seperti ini


  1. class HomeFragment : Fragment(), View.OnClickListener {

  2.  

  3.     override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,

  4.                               savedInstanceState: Bundle?): View? {

  5.         // Inflate the layout for this fragment

  6.         return inflater.inflate(R.layout.fragment_home, container, false)

  7.     }

  8.  

  9.     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

  10.         super.onViewCreated(view, savedInstanceState)

  11.         val btnCategory:Button = view.findViewById(R.id.btn_category)

  12.         btnCategory.setOnClickListener(this)

  13.     }

  14.  

  15.     override fun onClick(v: View) {

  16.         if (v.id == R.id.btn_category) {

  17.             val mCategoryFragment = CategoryFragment()

  18. val mFragmentManager = fragmentManager

  19. mFragmentManager?.beginTransaction()?.apply {

  20. replace(R.id.frame_container, mCategoryFragment, CategoryFragment::class.java.simpleName)

  21. addToBackStack(null)

  22. commit()

  23. }

  24. }

  25. }

  26. }






  1. public class HomeFragment extends Fragment implements View.OnClickListener {

  2.  

  3.     public HomeFragment() {

  4.         // Required empty public constructor

  5.     }

  6.  

  7.     @Override

  8.     public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,

  9.                              Bundle savedInstanceState) {

  10.         // Inflate the layout for this fragment

  11.         return inflater.inflate(R.layout.fragment_home, container, false);

  12.     }

  13.  

  14.     @Override

  15.     public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

  16.         super.onViewCreated(view, savedInstanceState);

  17.         Button btnCategory = view.findViewById(R.id.btn_category);

  18.         btnCategory.setOnClickListener(this);

  19.     }

  20.  

  21.     @Override

  22.     public void onClick(View v) {

  23.         if (v.getId() == R.id.btn_category) {

  24.             CategoryFragment mCategoryFragment = new CategoryFragment();

  25. FragmentManager mFragmentManager = getFragmentManager();

  26. if (mFragmentManager != null) {

  27. mFragmentManager

  28. .beginTransaction()

  29. .replace(R.id.frame_container, mCategoryFragment, CategoryFragment.class.getSimpleName())

  30. .addToBackStack(null)

  31. .commit();

  32. }

  33. }

  34. }

  35. }













  1. Setelah selesai, silakan jalankan aplikasi lagi. Klik tombol Ke Fragment CategoryAplikasi sudah berpindah tampilan tanpa berpindah activity.
    201811131131127aa0e3af13dea22195e18eaba488d437.gif

Bedah Kode 

FragmentTransaction

Anda telah belajar bagaimana berpindah tampilan tanpa harus berpindah activity. Jadi mudah kan dengan fragment? Mari kita breakdown satu demi satu hal yang baru saja Anda tulis:

Dimulai dari kode di dalam HomeFragment:


  1. val mCategoryFragment = CategoryFragment()

  2. val mFragmentManager = fragmentManager

  3. mFragmentManager?.beginTransaction()?.apply {

  4. replace(R.id.frame_container, mCategoryFragment, CategoryFragment::class.java.simpleName)

  5. addToBackStack(null)

  6. commit()

  7. }





  1. CategoryFragment mCategoryFragment = new CategoryFragment();

  2. FragmentManager mFragmentManager = getFragmentManager();

  3. if (mFragmentManager != null) {

  4. mFragmentManager

  5. .beginTransaction()

  6. .replace(R.id.frame_container, mCategoryFragment, CategoryFragment.class.getSimpleName())

  7. .addToBackStack(null)

  8. .commit();

  9. }





Berbeda dengan Activity yang memanfaatkan supportFragmentManager, Fragment menggunakan fragmentManager untuk mendapatkan FragmentManager. Setelah mendapatkannya, Anda dapat memulai transaksi pergantian fragment.
Apa yang beda di sini? Pastinya kita menggunakan method replace() dan bukan add() ketika ingin menempelkan sebuah fragment baru. Ya, dengan parameter input yang sama pada method add()method replace() akan mengganti objek fragment yang sedang tampil saat ini, yaitu HomeFragment dengan objek fragment yang baru, yaitu CategoryFragment.

addToBackStack

Anda pasti bertanya kenapa ada .addToBackStack(null) setelahnya? Kita menggunakannya karena objek fragment yang saat ini diciptakan masuk ke dalam sebuah fragment stack.  Nantinya ketika kita tekan tombol back, ia akan pop-out keluar dari stack dan menampilkan objek fragment sebelumnya HomeFragment.
Nah, mari kita coba menghilangkan addToBackStack pada kode sebelumnya, maka akan menjadi seperti ini:


  1. val mCategoryFragment = CategoryFragment()

  2. val mFragmentManager = fragmentManager

  3. mFragmentManager?.beginTransaction()?.apply {

  4. replace(R.id.frame_container, mCategoryFragment, CategoryFragment::class.java.simpleName)

  5. commit()

  6. }





  1. CategoryFragment mCategoryFragment = new CategoryFragment();

  2. FragmentManager mFragmentManager = getFragmentManager();

  3. if (mFragmentManager != null) {

  4. mFragmentManager

  5. .beginTransaction()

  6. .replace(R.id.frame_container, mCategoryFragment, CategoryFragment.class.getSimpleName())

  7. .commit();

  8. }




Jika Anda menghapus baris addToBackStack, menjalankan ulang aplikasi Anda, dan kemudian klik tombol back pada peranti, maka aplikasi akan langsung tertutup seperti ini:
2018111311351000d43e3fbd0042b58760865cb1c24592.gif
Asalas | Unlock Anime, Manhwa & Donghua Like Never BeforeFinasteriden: Unlock the Secrets of the Movie World!Marians Woman: Celebrating Beauty Around the WorldArheon - Unveiling the Secrets of Food & Origins WorldwideMPAPER The Ultimate Destination for Anime & Manga FansANMC21: Your Guide to Smarter Living and SuccessMV Agusta of Tampa: Your Automotive News HubTech and Play: Your Hub for Technology, Gaming, and GadgetsRebeccaSommer : Stories & Cultures from Around the WorldUETRABAJANDOJUNTOS - Inside the Music World’s Best-Kept SecretsVandelay Armor - Viral News and Global UpdatesGainesville Sun: Technology & Computers UnveiledGRFX Gaming Party Bus: Journey Through Gaming ErasHouse of Beauty: Celebrating the World's Most Beautiful WomenLearn Mistake: Wisdom for a Better LifeSports Hope Alive: Portal Olahraga DuniaWorld News TW - The Hottest Viral News & Global HeadlinesWriter Sujatha - Life Lessons & Struggles That Inspirehttps://128.199.185.186/https://143.198.89.74/https://165.227.47.178/https://170.64.208.214/https://170.64.192.239/https://46.101.102.216/LVONLINEtelegram lvonlinehttps://www.thecarbongenie.com/https://www.aievea-bijou.com/https://www.slashpolicy.com/https://www.benwestbeech.com/https://www.hh-bags.com/https://www.drupalforfacebook.org/https://www.lvonline.boats/https://www.lvoslot.com/https://www.lvobet.id/https://www.lvoslot.id/https://www.lvonline000.com/https://www.lvonline001.com/https://www.lvonline002.com/https://www.lvonline003.com/https://www.lvonline004.com/https://www.lvonline005.com/https://www.lvonline006.com/https://www.lvonline007.com/https://www.lvonline008.com/https://www.lvonline009.com/https://www.lvonline010.com/https://www.lvonlinepoker.com/https://www.lvonlinebola.com/https://www.lvonlinekasino.com/https://www.lvonline.io/https://www.lvonline.store/https://www.lvonline.online/https://www.situslvonline.us/situs bandar lvonlinehttps://146.190.97.83/https://143.198.209.134/https://188.166.246.204/https://167.172.83.179/https://togelhok.tv/https://www.togelhok.id/https://earthtoweb.com/https://www.elearningfacultymodules.org/https://www.how6youtoknowc.org/https://128.199.71.129/https://167.172.64.185/https://152.42.192.250/https://www.capcut88.com/https://www.capcut88.co/https://towsonsmiles.com/https://www.campur88.com/https://www.campur88.org/https://www.campur88.work/https://www.campur88.xyz/https://www.campur88.lol/https://www.nagacampur.biz/https://www.nagacampur.club/https://www.nagacampur.co/https://www.nagacampur.me/https://www.nagacampur.xyz/https://www.nasicampur88.com/https://165.232.175.185/https://152.42.164.228/https://152.42.194.203/https://152.42.169.214/https://www.campurslot.com/https://www.campurslot.id/https://www.campurslot.co/https://www.campurslot.org/https://www.campurslot.homes/https://www.campurslot.design/Badan Lembaga Pendidikan Ilmu Komputer SubangUniversitas Negeri JeparaLembaga Universitas Kristen MaranthaSMP 3 Negri Nganjukhttps://iklanmalay.com/https://promobola.comhttps://kapsychologists.comhttps://propertycloudsite.comSattar777 NewsVR Slot Online NewsRuby888 Online Slot NewsBerita Global Klik Agenslot228Agen Sloto SG777 NewsGold Club SlotOnline NewsAzar Marra Kech NewsBerita Sidney dan MancanegaraBerita Seputar Sumsel dan DuniaBerita Rehabilitasi Judi OnlineBerita Link Gacor TerupdateItalian Tuition News UpdateWPJS Online NewsBerita Agen Slot RoyalThai Slot Online NewsAll Online Game NewsOnline Game News UpdateAsian Lotre NewsBerita Demo Dana SlotBerita Kalbar ProvLocanda della Maria NewsWye Valley NewsBerita Agen Slot1004Berita Agen Slot33Agen Slot399 NewsPlayboy Slot Online NewsSlot Online BB Slot NewsSlot Online 911 News365 Slot Online NewsEat Atlah Newsambamali canadaInfo Seputar Sepakbolacentre thoughtBerita Hiburanopen etherpadras indo groupresistance manualPrediksi Shiowe want real newsthe poisoned pawnindonesia reclaimed teakswift kennedy and copullip passionmy passion foraim torontoPublic FlashesFriweb TeknologiIngenious Gamersthe late show gardensGishPuppy Newsslot danaOregon Farm Garden NewsViral Pulse GlobaljumpajpPromo Bola soccer Captivates The WorldKapsychologists World First The Science of Mental Health - Understanding Psychiatry: The Science of Mental HealthPropertyCloudSite How to Make Smarter Investments in Today’s MarketArnavichara Ultimate Guide Right Business SoftwareAuscare Disability A Comprehensive Guide to Retirement Homes Finding the Perfect Place to Enjoy Your Golden YearsSeries Mp4 The Future of Entertainment Streaming and Downloadable Video ExplainedAlogirlxinh How to Create a Successful Personal Page or Blog in 2024ihokibethttps://bengbulang-karangpucung.cilacapkab.go.id/https://comunicacion.unsa.edu.ar/https://seychellesbiodiversitychm.sc/https://www.925lms.com/https://www.guisseny.memoire.bzh/https://www.mobiliars.org/https://www.squashparkwieliczka.pl/
Asalas | Unlock Anime, Manhwa & Donghua Like Never BeforeFinasteriden: Unlock the Secrets of the Movie World!Marians Woman: Celebrating Beauty Around the WorldArheon - Unveiling the Secrets of Food & Origins WorldwideMPAPER The Ultimate Destination for Anime & Manga FansANMC21: Your Guide to Smarter Living and SuccessMV Agusta of Tampa: Your Automotive News HubTech and Play: Your Hub for Technology, Gaming, and GadgetsRebeccaSommer : Stories & Cultures from Around the WorldUETRABAJANDOJUNTOS - Inside the Music World’s Best-Kept SecretsVandelay Armor - Viral News and Global UpdatesGainesville Sun: Technology & Computers UnveiledGRFX Gaming Party Bus: Journey Through Gaming ErasHouse of Beauty: Celebrating the World's Most Beautiful WomenLearn Mistake: Wisdom for a Better LifeSports Hope Alive: Portal Olahraga DuniaWorld News TW - The Hottest Viral News & Global HeadlinesWriter Sujatha - Life Lessons & Struggles That Inspirehttps://128.199.185.186/https://143.198.89.74/https://165.227.47.178/https://170.64.208.214/https://170.64.192.239/https://46.101.102.216/LVONLINEtelegram lvonlinehttps://www.thecarbongenie.com/https://www.aievea-bijou.com/https://www.slashpolicy.com/https://www.benwestbeech.com/https://www.hh-bags.com/https://www.lvonline.boats/https://www.lvoslot.com/https://www.lvobet.id/https://www.lvoslot.id/https://www.lvonline000.com/https://www.lvonline001.com/https://www.lvonline002.com/https://www.lvonline003.com/https://www.lvonline004.com/https://www.lvonline005.com/https://www.lvonline006.com/https://www.lvonline007.com/https://www.lvonline008.com/https://www.lvonline009.com/https://www.lvonline010.com/https://www.lvonlinepoker.com/https://www.lvonlinebola.com/https://www.lvonlinekasino.com/https://www.lvonline.io/https://www.lvonline.store/https://www.lvonline.online/https://www.situslvonline.us/situs bandar lvonlinehttps://146.190.97.83/https://143.198.209.134/https://188.166.246.204/https://167.172.83.179/https://togelhok.tv/https://www.togelhok.id/https://earthtoweb.com/https://www.elearningfacultymodules.org/https://www.how6youtoknowc.org/https://128.199.71.129/https://167.172.64.185/https://152.42.192.250/https://www.capcut88.com/https://www.capcut88.co/https://towsonsmiles.com/https://www.campur88.com/https://www.campur88.org/https://www.campur88.work/https://www.campur88.xyz/https://www.campur88.lol/https://www.nagacampur.biz/https://www.nagacampur.club/https://www.nagacampur.co/https://www.nagacampur.me/https://www.nagacampur.xyz/https://www.nasicampur88.com/https://165.232.175.185/https://152.42.164.228/https://152.42.194.203/https://152.42.169.214/https://www.campurslot.com/https://www.campurslot.id/https://www.campurslot.co/https://www.campurslot.org/https://www.campurslot.homes/https://www.campurslot.design/Badan Lembaga Pendidikan Ilmu Komputer SubangUniversitas Negeri JeparaLembaga Universitas Kristen MaranthaSMP 3 Negri Nganjukhttps://iklanmalay.com/https://promobola.comhttps://kapsychologists.comhttps://propertycloudsite.comSattar777 NewsVR Slot Online NewsRuby888 Online Slot NewsBerita Global Klik Agenslot228Agen Sloto SG777 NewsGold Club SlotOnline NewsAzar Marra Kech NewsBerita Sidney dan MancanegaraBerita Seputar Sumsel dan DuniaBerita Rehabilitasi Judi OnlineBerita Link Gacor TerupdateItalian Tuition News UpdateWPJS Online NewsBerita Agen Slot RoyalThai Slot Online NewsAll Online Game NewsOnline Game News UpdateAsian Lotre NewsBerita Demo Dana SlotBerita Kalbar ProvLocanda della Maria NewsWye Valley NewsBerita Agen Slot1004Berita Agen Slot33Agen Slot399 NewsPlayboy Slot Online NewsSlot Online BB Slot NewsSlot Online 911 News365 Slot Online NewsEat Atlah Newsambamali canadaInfo Seputar Sepakbolacentre thoughtBerita Hiburanopen etherpadras indo groupresistance manualPrediksi Shiowe want real newsthe poisoned pawnindonesia reclaimed teakswift kennedy and copullip passionmy passion foraim torontoPublic FlashesFriweb TeknologiIngenious Gamersthe late show gardensGishPuppy Newsslot danaOregon Farm Garden NewsViral Pulse GlobaljumpajpPromo Bola soccer Captivates The WorldKapsychologists World First The Science of Mental Health - Understanding Psychiatry: The Science of Mental HealthPropertyCloudSite How to Make Smarter Investments in Today’s MarketArnavichara Ultimate Guide Right Business SoftwareAuscare Disability A Comprehensive Guide to Retirement Homes Finding the Perfect Place to Enjoy Your Golden YearsSeries Mp4 The Future of Entertainment Streaming and Downloadable Video ExplainedAlogirlxinh How to Create a Successful Personal Page or Blog in 2024ihokibethttps://bengbulang-karangpucung.cilacapkab.go.id/https://comunicacion.unsa.edu.ar/https://seychellesbiodiversitychm.sc/https://www.925lms.com/https://www.guisseny.memoire.bzh/https://www.mobiliars.org/https://www.squashparkwieliczka.pl/https://mok.edu.kz/https://www.mware.cloud/https://www.facilitiescoolingandheating.com.au/https://www.krillpay.ng/https://925worksuite.com/