I try create PreferenceFragment which must be opened via NavigationDrawer, but it does'nt work normal.
MainActivity.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private void setupNavigationDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
mDrawerLayout.closeDrawers();
setTitle(item.getTitle());
switch (item.getItemId()) {
...
case R.id.nav_one:
setFragment(3);
return true;
case R.id.nav_two:
setFragment(4);
return true;
case R.id.nav_settings:
getFragmentManager().beginTransaction()
.replace(R.id.content_main, new SettingFragment())
.commit();
return true;
}
return true;
}
});
}
public void setFragment(int position){
mFragmentTransaction = getSupportFragmentManager().beginTransaction();
Fragment fragment = null;
switch (position){
...
fragment = new OneFragment();
break;
case 4:
fragment = new TwoFragment();
break;
case 5:
break;
}
mFragmentTransaction.replace(R.id.content_main, fragment);
mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
mFragmentTransaction.commit();
}
}
SettingFragment.java
public class SettingFragment extends PreferenceFragment {
public SettingFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
}
And it looks like
enter image description here
The SettingFragment is inserted on top of the rest fragments and not destroyed after clicking other fragments.
This similar question enter link description here
not helped me.
Does anyone know the solution?
Solution: Use PreferenceFragmentCompat instead PreferenceFragment.
Related
HomeActivity
public class HomeActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
Context context;
private OrderFragment orderFragment;
private VideoFragment videoFragment;
private GoldFragment goldFragment;
private GoOutFragment goOutFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//changing color of status text
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomnavigationmenu);
FrameLayout frameLayout= (FrameLayout) findViewById(R.id.framelayout);
orderFragment= new OrderFragment();
videoFragment=new VideoFragment();
goldFragment= new GoldFragment();
goOutFragment= new GoOutFragment();
bottomNavigationView.inflateMenu(R.menu.service);
bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case 1:
setFragment(orderFragment);
return true;
case 2:
setFragment(videoFragment);
return true;
case 3:
setFragment(goldFragment);
return true;
case 4:
setFragment(goOutFragment);
return true;
}
return false;
}
});
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.framelayout,fragment);
fragmentTransaction.commit();
}
}
I have tried to pass object of an fragment class but getting error as setFragment Method Cannot be applicable to OrderFragment. as same for VideoFragment, goOutFragment and GoldFragment.
I have a problem with android studio. I use a fragment with a bottomNavigationView. It works fine if you click on the bottomNavigation. But if you simulate a click on the bottomNavigation it works for the first time and at the second time if you simulate the performclick again, it does not work.
I used also view.callOnClick(); and for the fragment add and remove fragment, but both do not function for my problem. I really appreciate it, if anyone can solve my problem.
Here is the Code:
`
public class ProfileFragment extends Fragment {
private Button send_order_button;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstaceState) {
return inflater.inflate(R.layout.profile_fragment, container,false);
}
#Override
public void onStart() {
send_order_button = (Button) getView().findViewById(R.id.auftrag_abschicken);
}
send_order_button.setOnClickListener(new View.OnClickListener() {
ProfilActivity pa = new ProfilActivity();
pa.changeFragment();
getActivity().finishActivity(ProfilActivity.class.hashCode());
}
}`
`
public class ProfilActivity extends AppCompatActivity {
public ProfilActivity() {}
public static Fragment selectedFragment = null;
public static BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navListener);
View view = bottomNavigationView.findViewById(R.id.nav_chat);
view.performClick();
}
public void changeFragment() {
// bottomNavigationView.setSelectedItemId(R.id.nav_store);
View view = bottomNavigationView.findViewById(R.id.nav_store);
view.performClick();
}
public BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_user :
selectedFragment = new ProfileFragment();
break;
case R.id.nav_chat :
selectedFragment = new MailFragment();
break;
case R.id.nav_store:
selectedFragment = new ShopFragment();
break;
}
try {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment, "fragment").commitAllowingStateLoss();
} catch (Exception e) {
e.printStackTrace();
};
return true;
}
};
}`
It looks like you're trying to set the default selected item in the BottomNavigationView. Why not just use bottomNavigationView.setSelectedItemId(R.id.nav_store); ?
This is my main activity where I am calling my fragments:
public class what extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private ListView mDrawerList;
private ArrayAdapter<String> mAdapter;
private FragmentTransaction fragmentTransaction;
NavigationView navigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_what);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
fragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content,new mainfrag());
fragmentTransaction.commit();
ActionBar actionBar= getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
navigationView=(NavigationView)findViewById(R.id.nav_view);
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(0).setChecked(true);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_main:
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setCheckedItem(R.id.nav_main);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new mainfrag());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("SGPA and CGPA Calculator"));
item.setChecked(true);
break;
case R.id.nav_savedcal:
navigationView.getMenu().getItem(0).setChecked(false);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setCheckedItem(R.id.nav_savedcal);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new savedFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("Saved Calculations"));
item.setChecked(true);
break;
case R.id.nav_upldoc:
navigationView.getMenu().getItem(0).setChecked(false);
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(3).setChecked(false);
navigationView.setCheckedItem(R.id.nav_upldoc);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new uploadedfragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("Uploaded documents"));
item.setChecked(true);
break;
case R.id.nav_site:
navigationView.getMenu().getItem(0).setChecked(false);
navigationView.getMenu().getItem(1).setChecked(false);
navigationView.getMenu().getItem(2).setChecked(false);
navigationView.setCheckedItem(R.id.nav_site);
mDrawerLayout.closeDrawers();
fragmentTransaction=getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_content, new resultsite());
fragmentTransaction.commit();
getSupportActionBar().setTitle(("VTU Results"));
item.setChecked(true);
break;
}
return false;
}
});
}
public boolean onOptionsItemSelected(MenuItem item ){
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE: {
finish();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
return;
}
}
This is my default fragment :
public class mainfrag extends Fragment {
private View view;
private AdView adView;
private Button button10;
private Button button11;
public mainfrag() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_mainfrag, container, false);
adView = view.findViewById(R.id.adView);
button10 = (Button) view.findViewById(R.id.button10);
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openmainactivity();
}
});
button11 = (Button) view.findViewById(R.id.button11);
button11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openscheme();
}
});
return view;
}
public void openmainactivity() {
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
}
public void openscheme(){
Intent intent=new Intent(getContext(), scheme.class);
startActivity(intent);
}
}
This is one of the other fragments:
public class savedFragment extends Fragment {
RecyclerView recyclerview;
adapter_sgpa recyclerAdapter;
ArrayList<POJO> sgpaArrayList;
public savedFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransaction tx = getChildFragmentManager().beginTransaction();
tx.replace(R.id.container, new sgpa_frag());
tx.commit();
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
Fragment fragment = null;
switch (id) {
case R.id.navigation_sgpa:
sgpa_frag sf = new sgpa_frag();
FragmentManager fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, sf).commit();
return true;
case R.id.navigation_cgpa:
cgpa_frag cf = new cgpa_frag();
fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().replace(R.id.container, cf).commit();
return true;
}
return false;
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_saved, container, false);
BottomNavigationView nav = (BottomNavigationView) v.findViewById(R.id.bottom_navigation);
nav.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
return v;
}
}
What changes should I make in this code so that I am able to move back from the other fragments to the main fragment on pressing back button ?
Maintain one boolean variable to check current fragment is MainFragment or not.
if its not MainFragment -> replace MainFragment
Else -> super.onBackPressed()
ex:
private boolean isMainFragment=true; //make it false when move to other fragment
#Override
public void onBackPressed() {
if(!isMainFragment){
isMainFragment=true;
//replace your MainFragment
}
else{
//your logic show dialog or super.onBackPressed()
}
}
Ithink I know what you need. have a look at the last part of this documentation
"You can add a fragment transaction to the back stack. The back stack keeps track of actions in your app which can be backtracked when the user clicks Android's standard "back" button on the device. If you add a fragment transaction to the back stack then the transaction can be backtracked (reversed) with a click on the back button on the device" quotet from Jenkov
simply do fragmentTransaction.addToBackStack(null) on your main activity before you do the commit this will allow you to travel back using the back button
if you always want to travel back to the main fragment then you want to only add the main fragment to the backstack that way on pressing the back button you will always land there
in this part of your oncreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_what);
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mToggle=new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
fragmentTransaction= getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_content,new mainfrag());
//HERE YOU PUT THE CODE V
fragmentTransaction.addToBackStack(null);
//HERE YOU PUT THE CODE ^
fragmentTransaction.commit();
ActionBar actionBar= getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// ALL THE OTHER STUFF COMMING AFTER
I want to develop a app with bottomnavigation ,In this I have 3 icons Home,Reminder,Settings .
I want to set a fragment as the default fragment of Home icon when the app is opened.
I have three fragments Home Fragment,Reminder Fragment and Settings Fragment.
MainActivity
public class MainActivity extends AppCompatActivity
implements Home.OnFragmentInteractionListener,
Reminders.OnFragmentInteractionListener,
Settings.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
switchToHomeFragment();
break;
case R.id.navigation_dashboard:
switchToRemindersFragment();
break;
case R.id.navigation_notifications:
switchToSettingsFragment();
break;
}
return false;
}
};
public void switchToHomeFragment() {
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_frame, new Home()).commit();
}
public void switchToRemindersFragment() {
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_frame, new Reminders()).commit();
}
public void switchToSettingsFragment() {
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(R.id.content_frame, new Settings()).commit();
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
This is my code and it works perfectly, serve yourself.
public class MyActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mBottomNav = findViewById(R.id.navigation);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
// init corresponding fragment
switch (item.getItemId()) {
case R.id.menu_home:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new HomeFragment()).commit();
break;
case R.id.menu_suggestion:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new SuggestionFragment()).commit();
break;
case R.id.menu_notification:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new NotificationFragment()).commit();
break;
case R.id.menu_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.container, new ProfileFragment()).commit();
break;
}
// update selected item
mSelectedItem = item.getItemId();
}
}
Just call this method switchToHomeFragment() inside onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
switchToHomeFragment()
// ^^^^^^^^^^^ call this to display home fragment when activity is created
}
or you can use setSelectedItemId ,inside onCreate, at the end
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
// recommended method, will highlight the icon as well
navigation.setSelectedItemId(R.id.navigation_home);
}
I need to implement the UI of my app, like the Instagram one. I need to switch from different fragments, with the usage of the bottom navigation view, but I need to keep state of the fragments, like I left them. How Can I achieve this?
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
item.setChecked(true);
switch (item.getItemId()) {
case R.id.action_formation:
if (homeFragment == null) {
homeFragment = new HomeFragment();
}
displayFragment(homeFragment);
break;
case R.id.action_result:
if (introResultFragment == null) {
introResultFragment = new IntroResultFragment();
}
displayFragment(introResultFragment);
break;
case R.id.action_market:
displayFragment(new MarketFragment());
break;
}
return false;
}
public void displayFragment(final Fragment fragment) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment, fragment.getClass().toString());
fragmentTransaction.commit();
}
It's been a long time but I want to offer my open source library in github which implements the same UX of Youtube and Instagram:
https://github.com/ZachBublil/ZNavigator
You got to add this dependency to your gradle:
compile 'com.zach.znavigator:znavigator:1.0.0'
The only thing you have to do is to pass the list of fragments you want to be in the BottomNavigationView:
public class SampleActivity extends NavigationActivity {
private BottomNavigationView navigationView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigationView = (BottomNavigationView) findViewById(R.id.navigationView);
LinkedHashMap<Integer, Fragment> rootFragments = new LinkedHashMap<>();
rootFragments.put(R.id.tab1, new FirstTab());
rootFragments.put(R.id.tab2,new SecondTab());
rootFragments.put(R.id.tab3, new ThirdTab());
init(rootFragments, R.id.container);
navigationView.setOnNavigationItemSelectedListener(this);
navigationView.setOnNavigationItemReselectedListener(this);
}
#Override
public void tabChanged(int id) {
navigationView.getMenu().findItem(id).setChecked(true);
}
}
If you want to open a new fragment as inner screen in one of the tabs you can do it by using ZNavigation class in the tab fragment:
ZNavigation.openChildFragment(getFragmentManager(),new ChildFragment());
just remember the active fragment, and use userVisiableHint to get active status in each fragment.
private Fragment currentFragment; // need to be init
private void switch2Fragment(Fragment target){
getFragmentManager().executePendingTransactions();
if(target.isAdded){
getFragmentManager().beginTransaction().hide(currentFragment).show(target).commit();
} else {
getFragmentManager().beginTransaction().hide(currentFragment).add(R.id.xxx, target).commit();
}
currentFragment.setUserVisibleHint(false);
currentFragment = target;
target.setUserVisibleHint(true);
}
private boolean isFragmentActive(Fragment target){
return target.getUserVisibleHint();
}