47

I have a fragment which creates its view inside onCreateView as you'd expect. However I want to change the view periodically.

My use case is that the fragment shows some data from a web service. When a user chooses an option from a list (another fragment), this fragment should switch to a progress bar, then once loaded, switch back to the data view.

I could make two fragments - the loading fragment, and the displaying fragment, but it seems that since this is an encapsulated event I'd rather do it all inside the one fragment.

Basically what I am asking, is what is the equivilent of setContentView inside a fragment.

9 Answers 9

33

You can use Fragment.getView(). This returns the view of the container which contains the Fragment. On that view, you can call removeAllViews. Then build your new views and add them to the view you got from getView().

http://developer.android.com/reference/android/app/Fragment.html#getView()

4
  • 5
    This answer is technically incorrect. getView() returns the View provided in onCreateView() not the container View
    – btalb
    Oct 3, 2014 at 8:55
  • Good point. It's still an answer to the question of @monkjack though.
    – bplayer
    Oct 3, 2014 at 9:36
  • 2
    getView() returns the view but doesn't have a removeAllViews() method. That method seems to be in the ViewGroup. Am I missing something?
    – Tim
    Feb 4, 2015 at 15:14
  • 1
    That's correct. But it's quite feasible that the View is going to be a ViewGroup. Not very robust though.
    – bplayer
    Feb 5, 2015 at 10:36
27

If for any reason, you want to change the whole fragment view (for example, asynchronous URL request that will change the view on success), you can either use the FragmentTransaction in the parent activity and create a new fragment on the fly.

Or you can keep the fragment and call a method of this fragment that will refresh itself. Example: In the parent activity, I build and store a list of fragments List<RefreshFragment> mFragmentList.

Here is the RefreshFragment class (and all my fragments extend this one in my example) :

public class RefreshFragment extends Fragment {
    protected Data data; // here your asynchronously loaded data

    public void setData(Data data) {
        this.data = data;
        // The reload fragment code here !
        if (! this.isDetached()) {
            getFragmentManager().beginTransaction()
               .detach(this)
               .attach(this)
               .commit();
        }
    }
}

Then in my activity asynchronous callback I can call :

for (RefreshFragment f : mFragmentList) f.setData(data);

So every fragment will be updated with the correct data and the currently attached fragment will update itself immediately. You have to provide you own onCreateView in the fragments of course.

The important thing is that a fragment can reload itself with getFragmentManager().

Nowdays, I would suggest using ViewModel for that purpose.

7
  • Problem is that the Fragment is never detached when you load your data or when user click on a button...
    – Waza_Be
    Dec 25, 2013 at 12:55
  • 1
    @Waza_Be I think it's a type and should look like this: if (!this.isDetached()) {.
    – sulai
    Nov 4, 2015 at 13:22
  • I believe this is the best approach to the updating fragment's view issue. When you follow the pattern in which you use Fragments as Views and Activity as a Controller it's great. It's very neat, it allows me to take advantage of inheritance and to gather all the view logic in one place - OnCreateView. I hope I will not find any significant disadvantages of this approach that would make me look for another one. Nov 25, 2015 at 16:51
  • 2
    This should be the answer this worked better than any other solution I tried. Thanks you saved my bacon!
    – JPM
    Feb 18, 2016 at 20:08
  • I think the Fragment is designed to work with fixed view. So I think to recreate the Fragment object is most proper decision here.
    – CodeToLife
    Jul 2, 2017 at 13:59
5

Create a "dummy" default view

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

</LinearLayout>

Inflate the "dummy" default view in the fragment's onCreateView method and use it as a placeholder to add views as needed

private LayoutInflater mInflater;
private ViewGroup mContainer;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
    mInflater = inflater;
    mContainer = container;

    View v =inflater.inflate(R.layout.home_view,container,false);
    placeholder = (ViewGroup) v;

    return placeholder;
}

To change the view to a new view you first remove all previous views then you inflate the new view and add

View newView = mInflater.inflate(R.layout.custom_dash, mContainer, false);
placeholder.removeAllViews();
placeholder.addView(newView);
0
4

You could use a FrameLayout to switch between your progress bar and data view, e.g.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView android:id="@+id/cover_image"
        android:scaleType="fitCenter"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
    <ProgressBar android:id="@+id/cover_progress"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_gravity="center"/>
</FrameLayout>

In onViewCreate() you would then store both views into instance fields

public View onCreateView(LayoutInflater inflater,
        ViewGroup container, Bundle savedInstanceState) {
    ...
    image = (ImageView) container.findViewById(R.id.cover_image);
    progress = container.findViewById(R.id.cover_progress);
    ...
}

and whenever you want to switch between the two (remember to do this in your UI/main thread), just do something like

progress.setVisibility(View.INVISIBLE);
image.setVisibility(View.VISIBLE);
3
  • 1
    ViewSwitcher is also convenient in this situation Dec 8, 2011 at 19:19
  • view.findViewById(R.id.cover_image); What is tha variable "view"?
    – Montaro
    Sep 6, 2013 at 5:20
  • 1
    @Montaro that should've been container, fixed in the answer. Thanks! Sep 6, 2013 at 10:49
3

Here's a simpler solution: save the inflater and container you receive in onCreateView, and use them later. For example:

private LayoutInflater mInflater;
private ViewGroup mRootView;

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mInflater = inflater;
    mRootView = container;
    return null;
}

public void someCallBackLater() {
    // mRootView.removeAllViews();   // in case you call this callback again...
    mInflater.inflate(R.layout.my_layout, mRootView);
}
1
1

U can use Transaction remove and add. I used an Fragment in which I can load any view. The Constructor of the Fragment has to have an integer, that integer is R.layout.... I just remove the old fragment and put some new. !!! It only works if you make this fragment a dynamic and not in the xml layout. Just create something like an LinearLayout R.id.fragment_layout

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.wundlist_fragmente);
    Log.v("WoundListActivity", "WoundListActivity gestartet...");

    Log.v("WoundListActivity", "Liste...");
    //dynamisch hinzufügen...
    wlf=new WoundListFragment();        
    fm.beginTransaction().add(R.id.fragment_layout,wlf).commit();

}

//If Menubutton Clicked change

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()==R.id.itemaddwound){
        Log.v("List", "neue Wunde Activity");

        fm.beginTransaction().remove(wlf).commit();
        fm.beginTransaction().add(R.id.fragment_layout, new NewWoundFragment()).commit();

    }

    return super.onOptionsItemSelected(item);
}
1

Using Solostaran14s response I am doing this now:

Interface:

public interface FragmentReattachListener {

    public void reAttach();

}

Fragment:

public class MyFragment extends Fragment implements  FragmentReattachListener {
//...

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    //...
    App.registerFragmentReattachListener(this);
    //...
}

//...    

@Override
public void reAttach() {
    FragmentManager f = getFragmentManager();
    if (f != null) {
         f.beginTransaction()
                    .detach(this)
                    .attach(this)
                    .commit();
        }
    }

}

from Application class:

private static void reattachFragments() {
        if (fragmentReattachListeners.size() > 0) {
            for (FragmentReattachListener listener : fragmentReattachListeners) {
                listener.reAttach();
            }
        }
    }
1
  • I approve : better with an interface. Nov 23, 2015 at 14:03
-1

This what worked for me:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_recipe, container, false);
    Button recipeBuyButton = (Button) v.findViewById(
            R.id.recipe_buy_button);
    Typeface tf = Typeface.createFromAsset(getActivity().getAssets(), "fonts/GE_SS_Two_Medium.otf");
    recipeBuyButton.setTypeface(tf);
    return v;
2
  • 1
    Why people doing negative vote on correct answer ? Nothing is wrong with this answer. +1 from my side. Jul 8, 2015 at 4:10
  • Because this answer doesn't have nothing to do with te current question.
    – Sierisimo
    Oct 26, 2015 at 19:15
-1

I have same problem, fragment.getView() always return null, although Fragment.onCreateView was already called before

we can not change content of fragment at runtime because my fragment was add to ViewPager so i try to use other method to get view:

 View view  =  viewPager.getChildAt(0);
 TextView text = (TextView) (view.findViewById(R.id.textView));
 text.setText("12345");

This problem now was resoloved, i hope can help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.