4

I tried the following code:

Intent in= new Intent(Activity1.this,Fragment.class);
startactivity(in);
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
Sunil Kumar
  • 75
  • 1
  • 1
  • 6

3 Answers3

6

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();
Bryan
  • 14,756
  • 10
  • 70
  • 125
3

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();
Sagar Chavada
  • 5,169
  • 7
  • 40
  • 67
1

Fragments not Open through Intent.

You should use Fragment manager.

Fragment fragment= new YourFragment(); 
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment); // fragment container id in first parameter is the  container(Main layout id) of Activity
transaction.addToBackStack(null);  // this will manage backstack
transaction.commit(); 

Sample Example of Fragment

public class MyFragment extends Fragment implements View.OnClickListener {



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view= inflater.inflate(R.layout.fragment_my, container, false);

    Button button1= (Button) view.findViewById(R.id.button1_Id);
    Button button2= (Button) view.findViewById(R.id.button2_Id);


    return view;
}

button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
   Fragment fragment= new YourFragment(); 
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment); // fragmen container id in first parameter is the  container(Main layout id) of Activity
transaction.addToBackStack(null);  // this will manage backstack
transaction.commit();
}
});

}
Harsh Bhavsar
  • 1,561
  • 4
  • 21
  • 39