How to start Fragment from onClick - android

I am using recyclerview in my app. I want to start a fragment when click on image view. But i don't know how to. Also i want to put data when starting fragment. I know how to start the activity with below code. But how can i start fragment same way?
Edited Code
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.layoutContent, frag);
ft.commit();

Fragments cannot be started, they must be added to a container.
Fragments aren't meant to function on their own, they need an enclosing Activity.
Having the following layout:
[...]
<FrameLayout android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?android:attr/detailsElementBackground" />
[...]
You place the fragment in it like such:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.commit();
You pass arguments to the fragment by using Bundle and creating the fragment as follows:
TestFragment newFragment = new TestFragment();
Bundle args = new Bundle();
args.putString("Hello world!");
newFragment.setArguments(args);
This has to be done before the transaction.
For further info refer to the official documentation
Note on edited code: you have to call the transaction from inside the Activity the FrameLayout is part of. Alternatively use a rather dirty workaround:
In Main:
public class Main extends Activity{
public static Main currentInstance;
public void onCreate(Bundle boomerang){
currentInstance = this;
}
}
In the Playlist activity then use Main.currentInstance.getSupportFragmentManager() etc.
But I wouldn't recommend it.

In order to start a fragment you need to make use of the fragment manager.
YourFragment yourFragmentInstance = YourFragment.newInstance("Hello", 12);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
//Fragment is hosted by an activity, and the activity must have a layout
//or a container for the fragment to be nested in, in this case it will be
//a FrameLayout with an id fragment_container
fragmentTransaction.replace(R.id.fragment_container, yourFragmentInstance);
fragmentTransaction.commit();
And you can pass in arguments to your fragment like this:
public class YourFragment extends Fragment {
public static YourFragment newInstance(String paramOne, int paramTwo) {
YourFragment fragment = new YourFragment();
Bundle b = new Bundle();
//set params/arguments for fragment
b.putString("param_one", paramOne);
b.putInt("param_two", paramTwo);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the params you passed in
Bundle bundle = getArguments();
String paramOne = bundle.getString("param_one");
String paramTwo = bundle.getInt("param_two");
}
}
Note: I've not tested this code.. This is just an idea :)

Related

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

This question already has answers here:
How to open a Fragment on button click from a fragment in Android
(3 answers)
Closed 6 years ago.
I tried the following code:
Intent in= new Intent(Activity1.this,Fragment.class);
startactivity(in);
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();
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();
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();
}
});
}

start Fragment from RecycleView Adapter Onclick

Hi I have A RecycleView Adapter and A button. I want that button to start a Fragment. I can start an activity but not a fragment. I have tried this Onclick method for my Button
#Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putParcelable("event", events.get(getLayoutPosition()));
Fragment fragment = new EditEventDetailFragment();
fragment.setArguments(bundle);
fragment.getFragmentManager().beginTransaction().replace(R.id.contentMainDrawer,fragment).commit();
}
But have error invoke null object (contentMainDrawer) is my Main activity content_layout.
Any help is much appreciate. The Fragment host recycle view is call from Mainactivity
Use below code for replace fragment
Fragment fragment = new EditEventDetailFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contentMainDrawer, fragment, "tag").commit();
if you are using this code inside adapter than replace getActivity() to ((Activity) context).
Hi I have found 2 answer that help whoever needed. The answer is to use the Activity that host the calling fragment. Many thanks #Mohit Suthar
Bundle bundle = new Bundle();
bundle.putParcelable("event", events.get(getLayoutPosition()));
Fragment fragment = new EditEventDetailFragment();
fragment.setArguments(bundle);
FragmentManager fragmentManager = ((MainActivity) context).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.contentMainDrawer, fragment, "tag").commit();

Get previous fragment android

I have a Layout were i keep swapping my two Fragments MainFragment and SecondFragment
I have an Activity Level Button and with its onclick I swap these fragments in the layout.
But I need to keep the same instance of FragA every time I switch back from FragB.
Below is the code that i used but the application crashes with a NullPointerError.
// When journey button menu is clicked [INSIDE THE MAIN ACTIVITY]
OnClickListener journeyBtnClick = new OnClickListener() {
#Override
public void onClick(View arg0) {
if(currentType==0){
InitThisFragment(1);
}else{
InitThisFragment(0);
}
}
};
private int currentType=0;
public void InitThisFragment(int type){
if(type==0){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//get the previously added MainFragment from the BackStack
Fragment mainFragment= getSupportFragmentManager().findFragmentByTag("main");
transaction.replace(R.id.abs_fragment_container,mainFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_ENTER_MASK);
transaction.commit();
}else{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.abs_fragment_container, new SecondFragment());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
}
currentType=type;
}
Before this I initialize the MainFragment in the OnCreate() of my Activity class;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.abs_fragment_container, new MainFragment());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); //add MainFragment in the BackStack
transaction.addToBackStack("main");
transaction.commit();
}
I the user clicks the Button
Initiate a New Fragment of the SecondFragment [No History of the
Previous Fragment]
Go Back to the MainFragment [In same state as it was while leaving
it]
Please help!
Thanks in advance.
If I have understood what you want to do, you can just call "FragmentManager.popBackStack()" if you are in the secondFragment.
So:
public void InitThisFragment(int type){
if(type==0){
getFragmentManager().popBackStack();
}else{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.abs_fragment_container, new SecondFragment());
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.commit();
}
currentType=type;
}
Put "main" tag in replace method.
transaction.replace(R.id.abs_fragment_container, new MainFragment(),"main");
tag parameter would work different for addToBackStack and replace method. According to android for tag parameter :
addToBackStack: An optional name for this back stack state, or null.
replace: Optional tag name for the fragment, to later retrieve the fragment with FragmentManager.findFragmentByTag(String).

how to move from one fragment to another fragment on button click

I am using the SherlockFragments library for the sliding menu.I have list of items as menu when
I click on item fragment get opened as an activity but it is a fragment.Now I am new to fragments.i don't know how to move from one fragment to another fragment.As in activity, we have intent to move to another activity.but in fragment I don't how to move to another fragment.I have a button in fragmentA.when I click on this button it moves to fragment B.
By googling I came to know that it has different cycles but anyhow I get toast msg when I click button
here is following code
public class Fragment2 extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.actionnetworklogin, container, false);
Button login = (Button)view.findViewById(R.id.login);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(v.getContext().getApplicationContext(),"login clicked", 5000).show();
}
});
return view;
}
}
Can someone please tell me how can I move one fragment to another fragment?
Is there any other method that I can use activities instead of fragments?
I have written code for all activities and java files but I don't know that sliding menu has fragmented and now I have to write all the code fragments.
It's simple Only three line code...
Fragment fragment = new SalesFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
This is the code I use to switch fragments inside a view:
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace([viewId], fragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.commit();
You can try this also:-
public void ButtonClick(View view) {
Fragment mFragment = new YourNextFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, mFragment ).commit();
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.frame_container,
new TeacherFragment()).commit();
FragmentTransaction fragmenttransaction = getSupportFragmentManager().beginTransaction();
FirstFragment regcomplainfragment = new FirstFragment();
fragmenttransaction.replace(R.id.content_frame, regcomplainfragment).addToBackStack("tag");
fragmenttransaction.commit();
//Below is the example
//In first Fragment
Fragment fragment = new YourFragmentClassName();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); android.support.v4.app.FragmentTransaction ft= fragmentManager.beginTransaction();
ft.replace(R.id.flContent, fragment);
Bundle args = new Bundle();
// Pass the values what you want to send to next fragment
args.putInt("Year", rYear);
args.putString("Month", rMonth);
args.putInt("Industry", rIndustry);
fragment.setArguments(args);
ft.commit();
//In Second Fragment
//In onCreateView Method get the values
int strYear= getArguments().getInt("Year");
String strMonth = getArguments().getString("Month");
strIndustry= getArguments().getInt("Industry");
//That's it very simple

How to add a dynamic number of fragments in android from an activity

I hava a fragment named DetailFragment which extends Fragment class with neccessary Override methods:
public class DetailFragment extends Fragment{
//Some neccessary methods are over here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.details, container, false);
return view;
}
}
I hava a main activity: FragmentActivity extends FragmentActivity which set content: setContentView(R.layout.main);. If I want to add DetailFragment from FragmentActivity, I have to declare a LinearLayout (or whatever layout) with android:id="#+id/container_fragment" inside the main.xml layout file. With this way, I can add a DetailFragment:
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
DetailFragment df = new DetailFragment();
ft.add(R.id.container_fragment, df);
ft.commit();
However, I can only add 1 DetailFragment into that container_fragment. If I want to add 2 or more DetailFragment from the activity, do I have to add 2 or more other container_fragment in the main.xml layout? And if not, what I should do and can you give an example? Thanks!
The layout can contain several fragments, you just have to specify different tags when calling the add function of the FragmentTransaction class.
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.container_fragment, new DetailFragment(), "df_1");
ft.add(R.id.container_fragment, new DetailFragment(), "df_2");
ft.commit();

Categories

Resources