I have an issue with fragment navigation in frame-layouts. Namely I cannot find out in which frame the fragment is currently being displayed in.
My setup is the following:
I have 3 parent fragments (PA, PB, PC), each with their own unique framelayouts. Additionally I have 3 Childfragments (CA,CB, CC) and two Grandchildfragments (GA, GB)
The parent fragments call the childfragments into the appropriate framelayouts (works fine), but now I want the childfragments to replace themselves with the appropriate grandchildren, but I have no way of finding out in which framelayout the childfragments are currently displayed in. (I hope that makes sense)
Pseudo-code example:
public class Parent extends Fragment{
//lots of stuff here
public void replaceFragmentWithChild(){
Fragment frg = new childFragment();
FragmentManager mgr = ((FragmentActivity) getActivity()).getSupportFragmentManager();
FragmentTransaction trx = mgr.beginTransaction();
trx.addToBackStack(null);
trx.replace(R.id.content_view_a, childFragment).commit();
}
}
public class Child extends Fragment{
//lots of stuff here
public void replaceFragmentWithGrandChild(){
Fragment frg = new GrandChildFragment();
FragmentManager mgr = ((FragmentActivity) getActivity()).getSupportFragmentManager();
FragmentTransaction trx = mgr.beginTransaction();
trx.addToBackStack(null);
//here is the problem. I would like to call trx.replace(GET-CURRENT-CONTENT-VIEW, frg)
trx.replace(???, frg).commit();
}}
Any input would be much appreciated.
Edit: Ok, I have found a possible solution by saving the ViewGroup Container in the onCreateView and passing that to the trx.replace function.
But unfortunately I am getting the following Message: java.lang.IllegalArgumentException: No view found for id 0x7f0c0057 (de.tel.quenference.activities:id/sara_content_view) for fragment PaperviewFragment{421da470 #2 id=0x7f0c0057} which makes little sense to me, because the view is the same one I am in,or?
What am I missing?
Ok, I figured it out and I sort of want to shoot myself.
First off, the 'No View Found' error stems from the fact, that my parentfragment did not call transaction.addToBackStack (I added it into my example code but not my production code...)
Just putting that in unfortunately did not fix everything, but I had to also change the ParentFragment to not call getChildFragmentManager, but rather the normal FragmentManager
otherwise the grandchildfragment would not appear in the frameLayout.
Basically my working code looks like this:
public class Parent extends Fragment{
//lots of stuff here
public void replaceFragmentWithChild(){
Fragment frg = new childFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
trx.addToBackStack(null);
trx.replace(R.id.content_view_a, childFragment).commit();
}
}
public class Child extends Fragment{
private ViewGroup locContainer;
//lots of stuff here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
locContainer = container;
return super.onCreateView(inflater, container, savedInstanceState);
}
public void replaceFragmentWithGrandChild(){
Fragment frg = new GrandChildFragment();
FragmentTransaction trx = getFragmentManager().beginTransaction();
trx.addToBackStack(
trx.replace(locContainer.getId(), frg).commit();
}}
Related
I've incorporated a horizontal slide navigation component (which required making the class extend Fragment). The slide part works fine. Here i have respective onClick() buttons which open a new activity. If I add a button into one of those activities I'm not finding a way to have the displayed activity subsequently refresh. I would think inflating an activity from a button within a fragment would be possible but anything I try stops the emulator.
There's not much to my code so far, so I'm not going to clutter my question with the associated layout part. Any help is certainly appreciated.
Fragment #1’s Java code
public class TasksFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tasks, container, false);
Button ID = (Button) rootView.findViewById(R.id.button_create_appraisal_rpt);
ID.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AppraisalReportActivity appraisalRptAct = new AppraisalReportActivity();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.child_fragment, appraisalRptAct);
fragmentTransaction.setTransition(fragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return rootView;
}
}
Fragment #1 (portion), which has the button that should initiate aa refresh of this Fragment #1 with Fragment #2
Fragment #2 that's to supersede/refresh the previous fragment when Fragment #1's button is clicked
I don't really understand what you mean. Do you want to click Button in Fragment to jump to another Activity?
If it is,I think maybe you can try use getActivity() to make Activity are working.
for example:
getActivity().startActivity(new Intent(getActivity(),Activity.class))
I hope my answer will help you
I'm new Android programming. Earlier I was working with activities, where i could implement onClick on an ImageButton and go to a different activity.
Now I need to do the same but using Fragments. I have a prototype with a menu that always appear on screen and can show different activities to the user. The different lactivities would be inside this container.
Now I want to place an ImageButton inside a fragment and make that the screen shows the next fragment. But I'm confused how to do it.
I have the following components:
Activity_main(java)+activity_main.xml (with menu)
Fragment1(java)+fragment1.xml(working normal)
Inside this layout I have an ImageButton and want to show Fragment2
Fragment2(java)+fragment2.xml
How should look Fragment1 to can call Fragment2?
I will be glad if the answer could be the clearest possible because I'm new on it, and maybe I could forgot an obvious step. Thanks
Simply make a method in your activity which will always change/replace fragment when you invoke it. something like
public void updateFragment(Fragment fragment){
//add fragment replacing code here
}
in your fragment, invoke it some thing like this
((YourActivity)getActivity()).updateFragment(new YourFragment());
since, it is just an idea which works fine but still you can improve the logic.
Actually, going from one fragment to another is almost similar to going from one activity to another. There are just a few extra lines of code.
First, add a new Java class named SingleFragmentActivity which would contain the following code-
public abstract class SingleFragmentActivity extends AppCompatActivity
{
protected abstract Fragment createFragment();
#LayoutRes
protected int getLayoutResId()
{
return R.layout.activity_fragment;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(getLayoutResId());
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null)
{
fragment = createFragment();
fm.beginTransaction().add(R.id.fragment_container, fragment).commit();
}
}
}
Make your activities in the following format-
public class SomeActivity extends SingleFragmentActivity
{
#Override
protected Fragment createFragment()
{
return SomeFragment.newInstance();
}
}
And your fragments like this-
public class SomeFragment extends Fragment
{
public static SomeFragment newInstance()
{
return new SomeFragment();
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_some, container, false);
return v;
}
}
After this everything has the same code as you have for activities except for one small detail which is your onCreateView(LayoutInflater, ViewGroup, Bundle) class. This is how you would write it-
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_some, container, false);
mTextView = (TextView)v.findViewById(R.id.some_text);
mButton = (Button)v.findViewById(R.id.some_button);
mTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
check();
}
});
return v;
}
And that is it!
Hi i hope you are already aware about the fragments and their uses but still here is a brief. They are child to an activity and an activity can have more than one fragment so you can update your layout without changing activity just by changing fragments.
You can found more on fragment here : https://developer.android.com/training/basics/fragments/index.html
Back to the original problem, supposed you are in MainActivity.java and you want to load fragment in it, so you do this to load fragment first time.
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, new Fragment1);
transaction.addToBackStack(null);
transaction.commit();
You will need this method to change fragment from another fragment, so add this in your MainActivity
public void changeFragment(Fragment fragment){
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frame, new Fragment1);
transaction.addToBackStack(null);
transaction.commit();
}
Now from a button click in this fragment
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((MainActivity)getActivity()).changeFragment(new Fragment2);
}
});
Hope it will help!
I am trying to add a fragment, then find a view inside said fragment, and add a view into it. However I keep getting a NullPointerException on this statement
FrameLayout container2 = (FrameLayout) fragment.getActivity().findViewById(R.id.content_frame);
Here is my code. Can someone tell me how to fix this please? thanks
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = new FragmentNavigationDrawer();
ViewGroup decor = (ViewGroup) getActivity().getWindow().getDecorView();
View child = decor.getChildAt(0);
decor.removeView(child);
fragmentTransaction.add(decor.getId(), fragment);
fragmentTransaction.commit();
FrameLayout container2 = (FrameLayout) fragment.getActivity().findViewById(R.id.content_frame);
container2.addView(child);
Just use a getter. Set a tag on your fragment so you can access it later, then either call getView() on your fragment to return its root view, or use a getter to access a specific View:
public class MainActivity extends AppCompatActivity {
//In onCreate
if (getFragmentManager().findFragmentByTag(FragmentNavigationDrawer.TAG) == null) {
getFragmentManager()
.beginTransaction()
.add(android.R.id.content, new FragmentNavigationDrawer(), FragmentNavigationDrawer.TAG)
.commit();
}
//Later, when you want to add said View:
FragmentNavigationDrawer frag =
(FragmentNavigationDrawer) getFragmentManager().findFragmentByTag(FragmentNavigationDrawer.TAG)
//Return the root view:
View fragRootView = frag.getView();
//Return a specific view:
frag.getUpdatableViewGroup().addView(newViewToAdd):
}
For your Fragment:
public class FragmentNavigationDrawer extends Fragment {
public static final String TAG = FragmentNavigationDrawer.class.getSimpleName();
FrameLayout updatableViewGroup;
//Can do this inside onCreateView() whilst inflating your Fragment's Views
//That's up to you.
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
updateableViewGroup = view.findViewById(R.id.updateable_view_group);
}
public FrameLayout getUpdatableViewGroup() {
return updateableViewGroup;
}
Be conscious of the Activity and Fragment life cycles however, and be careful not to attempt to access the Fragment's Views until they have finished inflating - onStart() of your Activity and later should be ok.
Please see the javadoc for FragmentTransaction.commit(). It says it will schedule a change to the fragment back stack. It doesn't happen immediately. It looks like you're expecting the fragment and its views to be instantly available.
Also, I'm really confused why you're reaching in a decor view to make changes. Usually you call out a view by id in the host activity's layout and make changes inside it.
I am having a hard time understanding how the fragment lifecycle relates to switching between fragments in the back stack. Please bear with me if my question exposes more than one misconception.
Here is my code:
public class SomeFragment extends Fragment {
private SomeCustomView customView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.some_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Create the child view
customView = (SomeCustomView) getView().findViewById(R.id.some_fragment_child_view);
customView.initializeMyCustomView();
}
}
As you can see, my fragment has a child view. The child view is a custom one. Here's code:
public class SomeCustomView extends SurfaceView implements SurfaceHolder.Callback {
private boolean aVariableWhichMustPersistForLifetimeOfApplication;
}
Whenever this fragment is added to the back stack and then later restored, the variable customView is recreated, and so I loose the value of aVariableWhichMustPersistForLifetimeOfApplication. This is creating all sorts of problems for me.
The application started out using an Activity that only displayed SomeCustomView and there were no fragments. Now I have to add functionality and so I have turned the custom view into a fragment, and thus I arrive at this problem.
I found an answer which works for me. The FragmentTransaction class has a number of methods which allow you to switch fragments in/out. (Android documentation for FragmentTransaction is here and a great StackOverflow explanation is here.)
In my case, I wanted SomeFragment to never loose the data contained in its view. To do this, use this code:
SomeFragment fragment = new SomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.activity_fragment_placeholder, fragment, "some_fragment");
transaction.commit();
and then later:
getFragmentManager().beginTransaction().hide(fragment).commit();
You can now add/attach a different fragment to R.id.activity_fragment_placeholder. Notice that I'm using hide() rather than replace(), that's the key difference that keeps the view from being destroyed. When you want the fragment back, you can use show() or Android will do this automatically when the user clicks "Back" if you use addToBackStack() when adding/attaching your other fragment.
in my app I'm using one activity and two fragments. The app uses a layout with a container so the fragments are added via transactions. The first fragment contains a listview and the other fragment a detail view for the listview items.
Both fragments use setRetainInstance(true). The fragments are added via a replace transaction and addToBackStack(null) is set. The listfragment contains an instance variable which holds some infos for the list. Now I'm changing to detail and press back and the instance variable is null. I read about setRetainInstance and addToBackStack and removed addToBackStack, but even then the instance variable is null.
Does anyone know what I might be doing wrong?
regards,
Thomas
setRetainInstance(true) will tell the FragmentManager to keep the fragment around when the containing Activity is killed and rebuilt for some reason. It doesn't guarantee that the Fragment instance will stick around after a transaction to add or replace. It sounds like your adapter is being garbage collected and you're not creating a new one.
A more generally easy solution would be to make a viewless Fragment to retain your ListAdapter. The way you do this is to create the Fragment, set the retain instance to true, and return null in the method onCreateView(). To add it, just called addFragment(Fragment, String) via the FragmentTransaction. You never remove or replace it, so it will always stay in memory for the length of the app. Screen rotations won't kill it.
Whenever your ListFragment is created, in onCreateView() get the FragmentManager and use either the method findFragmentById() or FindFragmentByTag() to retrieve your retained fragment from memory. Then get the adapter from that fragment and set it as your adapter for the list.
public class ViewlessFragment extends Fragment {
public final static string TAG = "ViewlessFragment";
private ListAdapter mAdapter;
#Override
public ViewlessFragment() {
mAdapter = createAdater();
setRetainInstance(true);
}
#Override
public void onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return null;
}
public ListAdapter getAdapter() {
return mAdapter;
}
}
public class MyListFragment extends ListFragment {
final public static String TAG = "MyListFragment";
#Override
public void onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View returnView = getMyView();
final ViewlessFragment adapterFragment = (ViewlessFragment) getFragmentManager().findFragmentByTag(ViewlessFragment.TAG);
setListAdapter(ViewlessFragment.getAdapter());
return returnView;
}
}
public class MainActivity extends FragmentActivity {
#Override
public void onCreate(Bundle icicle) {
// ... setup code...
final FragmentManager fm = getSupportFragmentManager();
final FragmentTransaction ft = fm.beginTransaction();
ViewlessFragment adapterFragment = fm.findFragmentByTag(ViewlessFragment.TAG);
if(adapterFragment == null) {
ft.add(new ViewlessFragment(), ViewlessFragment.TAG);
}
ft.add(R.id.fragmentContainer, new MyListFragment(), MyListFragment.TAG);
ft.commit();
}
}