Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open fragment on a button click from an activity either with intent and without intent in android? [duplicate]

Tags:

android

I tried the following code:

Intent in= new Intent(Activity1.this,Fragment.class);
startactivity(in);
like image 927
Sunil Kumar Avatar asked Dec 24 '22 03:12

Sunil Kumar


2 Answers

This is not how fragments work, fragments must be attached to an Activity. To get your desired effect you must either start a new Activity that contains the fragment you wish to show, or display the new fragment in the current Activity.

In order to decide between which approach to take, I would consider how you want the Fragment to affect the navigation of your interface. If you want the user to be able to get back to the previous view by using the Back button, you should start a new Activity. Otherwise you should replace a view in your current Activity with the new Fragment.

Though, it is possible to add a Fragment to the back stack, I would only attempt to do so if you are confident with the structure of your user interface.

To show a new fragment in the current Activity you can use a FragmentTransaction:

Fragment fragment = CustomFragment.newInstance();

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.replace(R.id.container_layout, fragment).commit();
like image 60
Bryan Avatar answered Apr 12 '23 23:04

Bryan


write this code in your onCreate or in your intent:

 FragmentManager fm = getSupportFragmentManager();
 YourFragment fragment = new YourFragment();
 fm.beginTransaction().add(R.id.main_contenier,fragment).commit();
like image 25
Sagar Chavada Avatar answered Apr 12 '23 23:04

Sagar Chavada