Сброс данных при переходе от одного фрагмента к другому с помощью нижней панели навигации
Я использую фрагмент нижней панели навигации в своем проекте. Когда он перемещается из одного фрагмента в другой, я не хочу терять состояние или данные. Как мне это сделать?
Это activity_main.xml
<RelativeLayout 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"
tools:context=".MainActivity">
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F9FAFD">
<FrameLayout
android:id="@+id/page_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bottom_bar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentBottom="true"
android:background="@android:color/white"
app:labelVisibilityMode="labeled"
app:menu="@menu/bottom_menu" />
</RelativeLayout>
А это MainActivity.java
package com.noval.tugas_6;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.noval.tugas_6.computer.ComputerFragment;
import com.noval.tugas_6.home.HomeFragment;
import com.noval.tugas_6.home_services.HomeServicesFragment;
import com.noval.tugas_6.phone.PhoneFragment;
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
private Fragment fragment;
private long exitTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottom_bar);
getFragmentPage(new HomeFragment());
setBottomNavigationView();
}
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
fragment = new HomeFragment();
break;
case R.id.computer_menu:
fragment = new ComputerFragment();
break;
case R.id.phone_menu:
fragment = new PhoneFragment();
break;
case R.id.home_services_menu:
fragment = new HomeServicesFragment();
break;
}
return getFragmentPage(fragment);
}
});
}
private boolean getFragmentPage(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.addToBackStack(null)
.replace(R.id.page_fragment, fragment)
.commit();
return true;
}
return false;
}
@Override
public void onBackPressed() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
exitTime = System.currentTimeMillis();
} else {
finish();
System.exit(0);
}
}
}
Это один из фрагментов, которые я использую PhoneFragment.java.
package com.noval.tugas_6.phone;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
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 com.noval.tugas_6.R;
public class PhoneFragment extends Fragment {
public int[] imgID = new int[]{R.drawable.infinix_zero, R.drawable.realme_c35,
R.drawable.galaxy_a33, R.drawable.samsung_galaxy_a13, R.drawable.samsung_galaxy_a23};
public String[] namaHP = new String[]{"Infinix Zero 5G", "Realme C35", "Samsung Galaxy A33 5G",
"Samsung Galaxy A13", "Samsung Galaxy A23"};
public String[] hargaHP = new String[]{"Rp3.600.000", "Rp2.150.000", "Rp4.700.000", "Rp2.500.000", "Rp3.500.000"};
ImageView imgHP;
TextView txtNama, txtHarga;
Button btnNext, btnPrevious;
int position = 0;
public PhoneFragment() {
// Required empty public constructor
}
// public static PhoneFragment newInstance() {
// PhoneFragment fragment = new PhoneFragment();
// Bundle args = new Bundle();
// fragment.setArguments(args);
// return fragment;
// }
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// if (getArguments() != null) {
//
// }
// }
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_phone, container, false);
}
// method ini dipanggil sesaat setelah onCreateView di atas dipanggil
// semua pembacaan view dan penambahan listener dilakukan disini
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
imgHP = (ImageView) getActivity().findViewById(R.id.imgHP);
txtNama = (TextView) getActivity().findViewById(R.id.txtNamaHP);
txtHarga = (TextView) getActivity().findViewById(R.id.txtHargaHP);
btnNext = (Button) getActivity().findViewById(R.id.btnNextHP);
btnPrevious = (Button) getActivity().findViewById(R.id.btnPreviousHP);
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
btnPrevious.setVisibility(View.GONE);
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
position += 1;
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
// jika posisi item yang terakhir, hilangkan tombol next
if (position == (imgID.length - 1)) {
btnNext.setVisibility(View.GONE);
} else if (position > 0) {
btnPrevious.setVisibility(View.VISIBLE);
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
position -= 1;
imgHP.setImageResource(imgID[position]);
txtNama.setText(namaHP[position]);
txtHarga.setText(hargaHP[position]);
if (position == 0) {
btnPrevious.setVisibility(View.GONE);
} else {
btnNext.setVisibility(View.VISIBLE);
}
}
});
}
}
Покажите, пожалуйста, как не потерять данные фрагмента при переходе на другой фрагмент. Спасибо.
1 ответ
потому что каждый раз, когда пользователь нажимает на нижнюю часть навигации, вы каждый раз создаете новый экземпляр фрагмента:
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
fragment = new HomeFragment();
break;
case R.id.computer_menu:
fragment = new ComputerFragment();
break;
case R.id.phone_menu:
fragment = new PhoneFragment();
break;
case R.id.home_services_menu:
fragment = new HomeServicesFragment();
break;
}
return getFragmentPage(fragment);
}
});
}
попробуй это :
private homeFragment = new HomeFragment();
private computerFragment = new ComputerFragment();
private phoneFragment = new PhoneFragment();
private homeServicesFragment = new HomeServicesFragment();
private Fragment active;
private final FragmentManager fm = getSupportFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
initFragment();
...
}
private void changeFragment(Fragment fragment, Bundle bundle) {
fm.beginTransaction()
.hide(active)
.show(fragment)
.commit();
active = fragment;
active.setArguments(bundle);
}
private void initFragment() {
fm.beginTransaction().add(R.id.frameLayout, homeFragment, homeFragment.class.getSimpleName()).commit();
fm.beginTransaction().add(R.id.frameLayout, computerFragment, computerFragment.class.getSimpleName()).hide(computerFragment).commit();
fm.beginTransaction().add(R.id.frameLayout, phoneFragment, PhoneFragment.class.getSimpleName()).hide(phoneFragment).commit();
fm.beginTransaction().add(R.id.frameLayout, homeServicesFragment, HomeServicesFragment.class.getSimpleName()).hide(homeServicesFragment).commit();
active = homeFragment;
changeFragment(homeFragment, null);
}
private void setBottomNavigationView() {
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
fragment = null;
switch (item.getItemId()) {
//id yang ada di menu bottom_menu.xml
case R.id.home_menu:
changeFragment(homeFragment, null);
return true;
case R.id.computer_menu:
changeFragment(computerFragment, null);
return true;
case R.id.phone_menu:
changeFragment(phoneFragment, null);
return true;
case R.id.home_services_menu:
changeFragment(homeServicesFragment, null);
return true;
}
return homeFragment;
}
});
}