How do I adapt an Activity in android from fragment transaction? - java

I have this code:
public void replaceFragment(int i) {
fragmentTransaction = getSupportFragmentManager().beginTransaction();
TextView headerName = (TextView) findViewById(R.id.HeaderName);
switch (i) {
// Login Fragment
case 0:
headerName.setText("Member Login");
fragmentTransaction.replace(R.id.main_container, new
LoginActivity());
break;
// Register Fragment
case 1:
headerName.setText("Sign Up");
fragmentTransaction.replace(R.id.main_container, new RegisterFragment());
break;
}
}
My problem is on the case 0, I put the other cases as examples. My login is not a Fragment, but an Activity. So how do I manage to keep it here? With an Intent?

Instead of
fragmentTransaction.replace(R.id.main_container, new
LoginActivity());
Use
Intent inntent = new Intent(this,LoginActivity.class);
startActivity(inntent);

Just build a new intent in case 0 and start your activity instead of trying to replace a fragment with activity which is impossible unless you turn your activity to fragment
If you need both you can turn your activity to fragment and then build an empty activity to contain it when necessary

Related

how to open specific fragment in onclick

i have 3 fragments inside an activity, it's a swipe menu with tabs viewpager
how to get into second fragment from another activity ?
what i mean by second fragment is when iam using this standart intent
Intent i = new Intent(getBaseContext(),Form_Mhs_04.class);
startActivity(i);
it went to first intent (case 0)
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch (position){
case 0 :
fragment = new form_mhs_04_fragment1();
break;
case 1 :
fragment = new form_mhs_04_fragment2();
break;
case 2 :
fragment = new form_mhs_04_fragment3();
}
return fragment;
}
You can't set 2nd fragment in TabLayout in this way. You have to pass the position that you want to select using intent.
Intent i = new Intent(this, Form_Mhs_04.class);
i.putExtra("TAB_POSITION", 2);
startActivity(i);
Then inside your Form_Mhs_04 activity get this position from intent and set TabLayout selected tab based on that.
int position = getIntent().getIntExtra("TAB_POSITION", 0);
TabLayout.Tab tab = tabLayout.getTabAt(position);
if(tab != null)
tab.select();

Fragment Transaction shows Tabs Fragment below

I'm making an app that has launches with a Swiping Tabs Fragment, but I also want to have a Preferences menu using Fragment Transaction. When I press the Settings button in my app, the preferences menu does appear and is interactive, but the layout seems to be transparent showing the Tabs below. Is there anything that can be done to fix this, or is there a better method?
Code that calls the Preferences Menu from the Options:
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
getFragmentManager().popBackStackImmediate();
break;
case R.id.logout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, Activity_Main.class));
break;
case R.id.action_settings:
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new Fragment_Settings()).addToBackStack(null)
.commit();
break;
}
return true;
}
Code that calls Tabs Fragments:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Fragment_Flower();
case 1:
// Games fragment activity
return new Fragment_Overview();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 2;
}
}
Initialising Transaction in onCreate:
startService(new Intent(this, SensorListener.class));
if (b == null) {
// Create new fragment and transaction
Fragment newFragment = new Fragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
//Replace whatever is in the fragment_container view with this
// fragment,
// and add the transaction to the back stack
transaction.replace(android.R.id.content, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
}
Any help will be greatly appreciated!
Just set background color in your layout file. It may avoid transparent backgound.

How to replace fragment of parent layout from child

I have looked at many of the similar question But still I'm unable to replace container layout (FrameLayout) of My Main Activity from a fragment that is visible in that container.
Here is what I'm trying to do I have a main activity with navigation drawer and On navigation drawer item click I'm changing fragment accordingly, I'm successful till this. These fragments are Login, Register, Categories, Contact Us etc. I'm changing/replacing fragments with FragmentManager, FragmentTransaction its method replace. Check the code below
public void changeFragment(int position) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
Fragment fragment = new Fragment();
BlankFragment blankFragment = new BlankFragment();
switch (position) {
case 0:
fragment = new FragMain();
break;
case 1:
fragment = new FragPrivacyPolicy();
break;
case 2:
fragment = new SettingsFragment();
break;
case 101:
fragment = new FragLogin();
break;
case 102:
fragment = new FragRegister();
break;
case 103:
fragment = new FragEditAccount();
break;
case 104:
fragment = new FragOrderHistory();
break;
case 105:
fragment = new FragForgotPass();
break;
case 106:
fragment = new FragOrderDetail();
break;
case 108:
fragment = new FragAboutUs();
break;
case 109:
fragment = new FragContactUs();
break;
case 110:
fragment = new FragMain();
break;
}
transaction.replace(R.id.flFragments, fragment);
transaction.commit();
}
Which is working fine as all my fragments extends Fragment. The problem comes when I try to call this method in one of the fragments visible in this mainActivity's container. Suppose I have a textView in FragLogin saying "Don't have an account Register" so on click this textView I have to open FragRegister in the same container of mainActivity. When I do it like this in my FragLogin App Crashes pointing to the transaction.commit();
MainActivity activity = new MainActivity();
activity.changeFragment(102);
And when I try like this
FragRegister fragRegister = new FragRegister();
// Fragment fragRegister = new FragRegister();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.Id.flFragments, fragRegister).commit();
It does not recognize the R.Id.flFragments as its inside the mainActivity not in FragLogin.
So how can I replace that FragRegister in mainActivity's container from FragLogin?
Dont use getChildFragmentManager() because it belongs to the fragment manager and the container that is holding current fragment is the activity container.Instead use getSupportFragmentManager().
Also see this stament
MainActivity activity = new MainActivity();
activity.changeFragment(102);
You are creating a new object of mainactivity which is already created.You have to call the activity method from fragments using getActivity().Call the changeFragment method like this.
((MainActivity)getActivity()).changeFragment(102);

How to navigate to Specific Fragment in NavigationDrawer from an Activity

My problem is that I am using NavigationDrawer with multiple fragments. I have an Activity. I am trying to return from the activity to Specific Fragment. I have tried to send an intent. It works but it always stay in that fragment due to the bundle value is not null. So if you have a way how to make the bundle null or you have a better solution than the intent I will be grateful. Thanks, all.
This Method is capable of switching the Fragments
public void DisplaySelectedScreen(int id) {
infoNom = this.getIntent().getExtras();
if (infoNom != null) {
id = Integer.valueOf(infoNom.getString("Fragment"));
}
infoNom = null ; //not Working
Fragment fragment = null;
switch (id) {
case R.id.nav_home:
fragment = new Home();
break;
case R.id.nav_info:
fragment = new Informations();
break;
case R.id.nav_cmd:
fragment = new Commandes();
break;
case R.id.nav_panier:
fragment = new Cart();
break;
case R.id.nav_contact:
fragment = new Contact();
break;
case R.id.nav_about_us:
fragment = new About_Us();
break;
case R.id.nav_logout:
ParseUser.logOut();
Intent intent = new Intent(Main.this, Welcome.class);
startActivity(intent);
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
You can clear the bundle using below method:
getIntent().removeExtra("key");
Hope It help you !
Ways to replace extras
void removeExtra(String name)
Remove extended data from the intent.
void removeFlags(int flags)
Remove these flags from the intent.
Intent replaceExtras(Intent src)
Completely replace the extras in the Intent with the extras in the given Intent.
Intent replaceExtras(Bundle extras)
Completely replace the extras in the Intent with the given Bundle of extras.
Hope this helps

Replacing a fragment with another fragment inside activity group

I have a fragment inside a group activity and I want to replace it with another fragment:
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
SectionDescriptionFragment bdf = new SectionDescriptionFragment();
ft.replace(R.id.book_description_fragment, bdf);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
It works fine when it is done as a seperate project without using activity group, every thing works fine in log cat as control goes inside getview(), but no view is visible, not even any exception arises, I want the book detail fragment to be replaced by section detail fragment.
Xml of book detail fragment has id book_description_fragment and xml for section description fragment has id section_description_fragment.
The above code is in onClick method of an item, I want that when user taps on an item in horizontal scroll view, then the fragment changes.
Fragments that are hard coded in XML, cannot be replaced. If you need to replace a fragment with another, you should have added them dynamically, first of all.
Note: R.id.fragment_container is a layout or container of your choice in the activity you are bringing the fragment to.
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();
Please see this Question
You can only replace a "dynamically added fragment".
So, if you want to add a dynamic fragment, see this example.
I've made a gist with THE perfect method to manage fragment replacement and lifecycle.
It only replace the current fragment by a new one, if it's not the same and if it's not in backstack (in this case it will pop it).
It contain several option as if you want the fragment to be saved in backstack.
=> See Gist here
Using this and a single Activity, you may want to add this to your activity:
#Override
public void onBackPressed() {
int fragments = getSupportFragmentManager().getBackStackEntryCount();
if (fragments == 1) {
finish();
return;
}
super.onBackPressed();
}
Use the below code in android.support.v4
FragmentTransaction ft1 = getFragmentManager().beginTransaction();
WebViewFragment w1 = new WebViewFragment();
w1.init(linkData.getLink());
ft1.addToBackStack(linkData.getName());
ft1.replace(R.id.listFragment, w1);
ft1.commit();
Use ViewPager. It's work for me.
final ViewPager viewPager = (ViewPager) getActivity().findViewById(R.id.vp_pager);
button = (Button)result.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(1);
}
});
hope you are doing well.when I started work with Android Fragments then I was also having the same problem then I read about
1- How to switch fragment with other.
2- How to add fragment if Fragment container does not have any fragment.
then after some R&D, I created a function which helps me in many Projects till now and I am still using this simple function.
public void switchFragment(BaseFragment baseFragment) {
try {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
if (getSupportFragmentManager().findFragmentById(R.id.home_frame) == null) {
ft.add(R.id.home_frame, baseFragment);
} else {
ft.replace(R.id.home_frame, baseFragment);
}
ft.addToBackStack(null);
ft.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
enjoy your code time :)
you can use simple code its work for transaction
Fragment newFragment = new MainCategoryFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame_NavButtom, newFragment);
ft.commit();
You Can Use This code
((AppCompatActivity) getActivity()).getSupportFragmentManager().beginTransaction().replace(R.id.YourFrameLayout, new YourFragment()).commit();
or You Can This Use Code
YourFragment fragments=(YourFragment) getSupportFragmentManager().findFragmentById(R.id.FrameLayout);
if (fragments==null) {
getSupportFragmentManager().beginTransaction().replace(R.id.FrameLayout, new Fragment_News()).commit();
}
I change fragment dynamically in single line code
It is work in any SDK version and androidx
I use navigation as BottomNavigationView
BottomNavigationView btn_nav;
FragmentFirst fragmentFirst;
FragmentSecond fragmentSecond;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
fragmentFirst = new FragmentFirst();
fragmentSecond = new FragmentSecond ();
changeFragment(fragmentFirst); // at first time load the fragmentFirst
btn_nav = findViewById(R.id.bottomNav);
btn_nav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch(menuItem.getItemId()){
case R.id.menu_first_frag:
changeFragment(fragmentFirst); // change fragmentFirst
break;
case R.id.menu_second_frag:
changeFragment(fragmentSecond); // change fragmentSecond
break;
default:
Toast.makeText(SearchActivity.this, "Click on wrong bottom SORRY!", Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
public void changeFragment(Fragment fragment) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_layout_changer, fragment).commit();
}
In kotlin you can do:
// instantiate the new fragment
val fragment: Fragment = ExampleFragment()
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.book_description_fragment, fragment)
transaction.addToBackStack("transaction_name")
// Commit the transaction
transaction.commit()
This will work if you're trying to change the fragment from another fragment.
Objects.requireNonNull(getActivity()).getSupportFragmentManager()
.beginTransaction()
.replace(R.id.home_fragment_container,new NewFragment())
NOTE As stated in the above answers, You need to have dynamic fragments.
You can use fragment-ktx
// If you are in fragmet
childFragmentManager.beginTransaction()
// or if you are in activiry
supportFragmentManager.beginTransaction()
// Create and commit a new transaction
supportFragmentManager.commit {
setReorderingAllowed(true)
// Replace whatever is in the fragment_container view with this fragment
replace<ExampleFragment>(R.id.fragment_container)
}
To replace a fragment with another one do this, Note that R.id.fragment comes from the id that you give to the first tag of the fragment in the XML.
barAudioPlaying.setOnClickListener(view -> {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment,new HomeFragment())
.commit();

Categories