Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

android - Refresh or force redraw the fragment

I have a fragment that inflates an xml layout. My requirement is to update the text size on all my views inside my fragment when my Activity is resumed. I tried

    fragment.getView().invalidate();

which didn't seem to do the work. I also tried

    fragment.getView().requestLayout();

which didn't work either.

On another activity, I have a ListFragment which needs to do the same thing. I tried

    listfragment.getListView().invalidate();

which did the trick, refreshing my list view and redrawing all the items inside it.

I don't understand why one works but not the other.

I have also seen people recommending initiating a fragment transaction and replacing the current fragment with a new one, and it has kept me wondering

  1. Why should I create a whole new fragment and replace my current fragment when all I need is to refresh the text on the views that my fragment contains.

  2. Fragment transaction method will prevent me from defining my fragment in the layout xml of my activity and I will have to programatically insert the fragment at the right position.

Is there any simple approach to this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I do not think there is a method for that. The fragment rebuilds it's UI on onCreateView()... but that happens when the fragment is created or recreated.

You'll have to implement your own updateUI method or where you will specify what elements and how they should update. It's rather a good practice, since you need to do that when the fragment is created anyway.

However if this is not enough you could do something like replacing fragment with the same one forcing it to call onCreateView()

FragmentTransaction tr = getFragmentManager().beginTransaction();
tr.replace(R.id.your_fragment_container, yourFragmentInstance);
tr.commit()

NOTE

To refresh ListView you need to call notifyDataSetChanged() on the ListView's adapter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...