I tried to add a fragment on button click action inside an adapter which extends a BaseAdapter.
But to use fragments the class has to extend Fragment to use the FragmentManager.
I've imported :
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
But still facing an error here:
FragmentManager fragmentManager=getFragmentManager();
I've also tried to give the activity reference when getting the FragmentManager,it gave more errors.
Any help would be much appreciated.
Thanks in advance.
Here is my adapter code:
Drawer item(view) onclick action:
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (position == 1)// Home
{
Home2Fragment fragment = new Home2Fragment();
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.add(fragment, null);
fragmentTransaction.commit();
}
}
});
Because importing Fragments from support library so, use getSupportFragmentManager method to get FragmentManager :
FragmentManager fragmentManager=<Activity_Context>.getSupportFragmentManager();
Need to use FragmentActivity context to access FragmentManager and also make sure extending FragmentActivity instead of Activity.
It is considered good practice to use let Adapters be an inner class of the List that uses them. That gives the adapter full access to the class using them and if it's a fragment, you can use the fragment manager.
Related
I need help with code snippet for replacing a fragment with another fragment on click of a button.
Here is the XML for the MainActivity
What can i do to resolve this error?
Tried searching the web only to come up with the same solution.
If somebody could please help me out on this.
Code for Main.Activity
public class MainActivity extends AppCompatActivity{
Button button1, button2, button3, button4;
Fragment fragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button)findViewById(R.id.layout1);
button2=(Button)findViewById(R.id.layout2);
button3=(Button)findViewById(R.id.layout3);
button4=(Button)findViewById(R.id.layout4);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragment = new Fragment2();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frag, fragment);
transaction.commit();
}
});
I saw few issues in your code:
If you add your fragment inside xml file, you cant remove/replace it in the future. As described from Google Page:
Note: When you add a fragment to an activity layout by defining the fragment in the layout XML file, you cannot remove the fragment at runtime. If you plan to swap your fragments in and out during user interaction, you must add the fragment to the activity when the activity first starts, as shown in the next lesson.
Your error may come from casting fragment. You should check your Fragment2. it maybe a support fragment.
Update
Here's the link to learning more about creating/adding fragment: Google Guide
Based on your comments, you should check what you did import in the Fragment2 layout (import android.support.v4.app.Fragment; or not). Are all your fragments from the same package or not?
The variable 'fragment' is an object of class Fragment and you are creating it as a object of class Fragment2 (which is a subclass of Fragment). This is not valid hence it's showing an error. Also to replace any fragment the fragment it should be inside a container view (usually a FrameLayout) and then you can use the replace transaction to replace it on the button click. The code should be as follows:
XML Code:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="frameLayout" />
Java Code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction().replace(R.id.frameLayout,fragment2).commit();
}
});
Just replace your fragment in your xml with a FrameLayout.
Now within button's onClickListener
YourFragment fragment = YourFragment.getInstance();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frLayout, fragment, "TAG");
transaction.commit();
Hope that helps.
You should try
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
in xml insted of fragment
and try this
Fragment2 frag2 = new Fragment2();
getSupportFragmentManager().beginTransaction().replace(R.id.frag, frag2);
in java code.
I created a class called SlidingFragment that extends from Fragment, and in my MainActivity I put these lines:
MainActivity.java :
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpView();
setUpFragment();
}
void setUpView(){
setContentView(R.layout.activity_main);
}
void setUpFragment(){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
SlidingFragment fragment = new SlidingFragment();
transaction.replace(R.id.sample_content_fragment, fragment);
transaction.commit();
}
}
The problem is that the replace() method of the FragmentTransaction class can't recognize the second argument fragment which is a SlidingFragment object. I get this:
wrong second argument type found.'SlidingFragment' required 'android.support.v4.app.Fragment'.
replace(int,android.support.v4.app.Fragment)
to
replace(int,com.example.g514110.IhmSlidingTabs.SlidingFragment)
I understand the problem, but I don't know how to solve it.
Can someone please help.Thanks
Do that SlidingFragment extends
import android.support.v4.app.Fragment;
and not
android.app.Fragment
Make sure your SlidingFragment is extending android.support.v4.app.Fragment. Based on this compiler error, it currently is not.
Before I am also facing this issue , I did few changes . Now it's Workking Fine
New frgment page Eg : home_fragment
import android.support.v4.app.Fragment;
Main XML Design must contain any layout with your id eg :
android:id="#+id/fragment_container"
Main Java Class
import android.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
Click Event
home_fragment fragment = new home_fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
This Code Workking Fine For Me
I have an activity containing multiple fragments. Activity initially have fragment and in it have two buttons. Upon clicking this button I have to replace the fragment by new fragment. Each fragment has various widgets and replace the current fragment as various events.
This is my problem. How can I achieve this?
Suggest me ideas.
you can replace fragment by FragmentTransaction.
Here you go.
Make an interface.
public interface FragmentChangeListener
{
public void replaceFragment(Fragment fragment);
}
implements your Fragment holding activity with this interface.
public class HomeScreen extends FragmentActivity implements
FragmentChangeListener {
#Override
public void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager = getSupportFragmentManager();;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment, fragment.toString());
fragmentTransaction.addToBackStack(fragment.toString());
fragmentTransaction.commit();
}
}
Call this method from Fragments like this.
//In your fragment.
public void showOtherFragment()
{
Fragment fr=new NewDisplayingFragment();
FragmentChangeListener fc=(FragmentChangeListener)getActivity();
fc.replaceFragment(fr);
}
Hope this will work!
NOTE: mContainerId is id of the view who is holding the fragments inside.
You should override Fragment's onString() method as well.
Well even I am learning android...
I solved same problem recently, "How to Change Fragment On button's click event".
buttonName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction fragmentTransaction = getActivity()
.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame1, new Homefragment());
fragmentTransaction.commit();
}
});
Here frame1 is id of FrameLayout which have define in my DrawerLayer's XML.
So now whenever I want fragment transaction I use this code. Each time it will replace frame1 instated of your last fragment.
FragmentTransaction fragmentTransaction = getActivity()
.getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frame1, new newfragment());
fragmentTransaction.commit()
Hope this will help..
You can use the following to replace a fragment on button click of that fragment:
getFragmentManager().beginTransaction().replace(R.id.main_content, new insertFragmentNameHere()).addToBackStack(null).commit();
Define an interface and call it IChangeListener (or something like that) and define a method inside which will do the work (ex, changeFragment()) (or call another method which will do the work) for changing the fragment).
Make your activity implement the interface, or make an anonymous class within the activity implement it.
Make a paramerized constructor of your fragment, which accepts a IChangeListener parameter.
When initializing the fragment, pass your IChangeListener implementation (the anonymous class or the activity, implementing it)
Make the onClick listener of the button call the changing method of the IChangeListener.
From the future 2017 and after, there exists different libraries that triggers Events using Bus and now you can use it to tell the activity when an event is trigger in a fragment that it owns.
Refer to:
RxBus with RxJava
You can check new architectures suggested by Google
ViewModel
Don't use the approach in the accepted answer, get really ugly with more than 3 different events from fragments
you can try this code it's work fine with me , inflate the layout to view , Define the buton and on click ,
Button btn_unstable;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home,container,false);
btn_unstable = (Button)view.findViewById(R.id.btn_unstable);
btn_unstable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.fragment_replace, new UnstableFragment()).commit();
}
});
return view;
}
I would like to add a FragmentActivity in the activity layout. In order to make fragment transactions (such as add, remove, or replace a fragment), the api guides say that I first need to get an instance of FragmentTransaction from your Activity and then add a fragment using the add() method specifying the fragment to add and the view in which to insert it. Ok pretty straightforward so far, but what should I do in the FragmentActivity case?
AllEventsFragments events;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if ( savedInstanceState == null )
{
events = new AllEventsFragments();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.content_frame, events,"events");
// Commit the transaction
transaction.commit();
}
}
in which AllEventsFragments is defined as follows:
public class AllEventsFragments extends FragmentActivity implements ActionBar.TabListener
{
...
}
Since the add method accepts a Fragment as second argument the error returned is:
The method add(int, Fragment, String) in the type FragmentTransaction is not applicable for the arguments (int, AllEventsFragments, String)
I would like to add a FragmentActivity in the activity layout.
You are trying to nest activities. That is not supported via fragment transactions, and what little support there ever was for it has been deprecated for ~2.5 years.
However, you can move much of the AllEventsFragments logic into a Fragment, which can then be used from both AllEventsFragments and wherever else you are trying to use it.
I follow this tutorial to create a viewpager gallery http://www.androidbegin.com/tutorial/android-viewpager-gallery-images-and-texts-tutorial/.
I added a onClick listener to the ImageView in the PagerAdapter.
I want to open a fragment when the imageview is clicked. How can I do that?
public void onClick(View v) {
// TODO Auto-generated method stub
transaction = getFragmentManager().beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.frameContent, new TravelogueFragment()).commit();
}
I alreary tried that code inside my class which extend PagerAdapter but Im getting an error with the getFragmentManager() it says that getFragmentManager is undefine.
You have to use interface and listener. You can see code here. In my case, I replace Fragment when list item click, so you'll only need to adapt it and it will work.