I am new to fragment concept. In my app I have to save user preferences. I have gone through this doc.
Prepared my preferences xml file and PreferenceFragment file. Everything is fine up to now.
My problem is, I have to add the following code in my onCreate() method of my MainActivity
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
It is showing on Main screen. But I want to launch this on a button click method
onSettingsClicked(){
// launch preferces screen
}
And I want to display it as a separate screen. How can I do that?
You need to implement the concept of fragmentTransaction.
You need to do the following things-
Create a new Fragment.xml to display the button.
Invoke the new fragment from the onCreate();
Get the Button on the Fragment view.
On Button onclick listener replace the the fragment with the SettingFragment().
Done!
Check out this FragmentTransaction Tutorial, it will guide you-
Do the following changes like -
// Code not accurate, may be some syntax error
#Override
public void onCreate()
{
// super and other stuff
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new NewFragment())
.commit();
Button btn = (Button)findViewById(R.id.button01);
btn.setOnClickListener(new OnClickListener(){
#override
public void onClick(View v)
{
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(android.R.id.content, new new SettingsFragment())
.commit();
}
});
}
Instead of using fragementTransaction you can use preferenceFragement :
How do you create Preference Activity and Preference Fragment on Android? by WannaGetHigh
Related
I have a problem with fragments. In my xml file I have a fragment already set there, I want with the click of a button replace it with another fragment. So with my code I can replace the fragment with the one that I want on the click of the button, but the first fragment wont disappear, so I can still see it under my second fragment, the code it's this:
public class MainActivity extends AppCompatActivity {
FragmentManager fragmentManager;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment,new BlankFragment2());
fragmentTransaction.addToBackStack(null).commit();
}
});
}
}
Set a background color of the root layout of the second fragment and put clickable and focusable true in xml file. It will make disappear of the first fragment and also disable the clicks of first fragment when showing another fragment.
Remove addToBackStack(null).
That stores the Fragment and keeps it attached so that calling popBackStack() will remove the top Fragment and replace it with the previous.
correctly implementing addToBackStack will help in this case and many other
addToBackStack takes an argument which is called task record TAG , To perform a transaction later on , you can use this tag to remove back stack up to a point
For more understanding read
https://medium.com/#bherbst/managing-the-fragment-back-stack-373e87e4ff62
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 have navigation bar on my app. Using that has created fragments. I added regular activities to the app and I have found how to go from a Fragment page to an activity page with using the onclick method.
By the click of a button I want to go from an activity page to a fragment page. How do I go about that?
Thank you
apply on click listner on the button and apply below code :-
Fragment fragment = new VehiclesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.container,fragment).commit();
If you want to close the current activity to go back to your Fragment-container Activity you may call the finish() method or onBackPressed() method (in case you're not overriding it).
If you want to bring a fragment to the current activity you must have a fragment container and attach it with:
getSupportFragmentManager().beginTransaction.add(R.id.container, fragment, TAG).addToBackStack().commit();
Try this code..
btn.setOnClickListener(new View.OnClickListener()){
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(),FragmentTest.class);
getActivity().startActivity(intent);
}
});
If you want to move around in fragment then you have to be using either navigation bar clicks on tabs or use this from one fragment to another on a click of button .. like this
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = Fragment.instantiate(MainActivity.this, <name of the fragment>);
Bundle bundle = new Bundle();
bundle.putBoolean(ALL_EVENTS, true);
fragment.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.container, fragment).commit();
Simply use this:
Intent(view.context, DestinationActivity::class.java).also {
view.context.startActivity(it)
}
I have a Main Menu and created a fragment and its layout.
Now I can't seems to start fragment when user presses a button on main menu.
main menu has its own layout.
now is there anyway i could initialize it from a button?
Button bt = (Button)findViewById(R.id.button1);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainMenu.this, ExercisesFragment.class));
}
});
}
I tried it by this but it gives error saying
Fragment cannot be cast to android.app.Activity
You add fragments using fragment manager:
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ExercisesFragment fragment = new ExercisesFragment();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
read more on fragments, start here:
http://developer.android.com/guide/components/fragments.html
FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
ft.add(R.id.main_fragment, your_fragment);
ft.addToBackStack("ifneeded");
ft.commit();
You are doing it wrong! Intents are not used to load a fragment.
Solution is to use fragment transactions
to dynamically load the fragment you wish to bring into focus.
Here is what you need to do:
Have a container for the fragment inside the layout of you activity
Example: Assuming the layout resource of my activity is activity_main.xml, I would have a container like so
Follow this guide to create a Fragment
Assuming you already have a fragment setup with name AbcFragment, use fragment transactions to load the fragment into the container that you just created, whenever the user clicks on the button:
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager()
.beginTransaction()
.replace(R.id.fragment-container, new AbcFragment)
.commit();
}
});
I am launching some fragments from my options menu, for example a preference fragment and a dialog fragment.
When I open the preferences fragment and hit the back button the entire activity closes. This is not the case for the dialog fragment that works as I'd expect.
Could someone explain why this is happening and what is the accepted way of handling please? :)
To launch preference fragment:
getFragmentManager().beginTransaction()
.add(android.R.id.content, new SettingsFragment())
.addToBackStack("settings")
.commit();
Related to my answer here.
I had the exact same problem with the preferences fragment. It seems most people must give up and use a Preference Activity instead.
Your first problem that you are going to encounter is that you need to use replace instead of add when launching the fragment. That code should change to look like so:
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.addToBackStack("settings")
.commit();
As for handling the back button, it appears that the "back stack" is something that is not automatically triggered with the system back button. My solution was to manually pop the back stack from the onBackPressed override:
#Override
public void onBackPressed()
{
if (inSettings)
{
backFromSettingsFragment();
return;
}
super.onBackPressed();
}
Whenever I navigate to my preferences fragment, I set the inSettings boolean to true in the activity to retain that state. Here is what my backFromSettingsFragment method looks like:
private void backFromSettingsFragment()
{
inSettings = false;
getFragmentManager().popBackStack();
}
If there is not any clear reason you named your back stack state, use null as argument:
getFragmentManager().beginTransaction()
.add(android.R.id.content, new SettingsFragment())
.addToBackStack(null)
.commit();