I am developing application which contains 2 fragments and i want to show hide according to my need. Following code has simple example of my problem. This simple Fragmentactivity contains 1 button and one listfragment.
This simple example works flawless. but i am not satisfied with show hide fragment. If you remove layout.setVisibility(View.GONE); from the code then ft.hide(f); will not hide fragment. In fact we are not hiding fragment we are hiding container.
My Question is, IS this a way to show hide fragments? If not then please explain with tested example How to hide and show Fragments because lots of people are facing this problem.
public class MainActivity extends FragmentActivity implements OnClickListener { Fragment1 f; Button b; LinearLayout layout; Fragment myf; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b = (Button) findViewById(R.id.button1); layout = (LinearLayout) findViewById(R.id.ll); f = new Fragment1(); } @Override public void onClick(View v) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); if (f.isHidden()) { ft.show(f); layout.setVisibility(View.VISIBLE); b.setText("Hide"); } else { ft.hide(f); b.setText("Show"); layout.setVisibility(View.GONE); } ft.commit(); // TODO Auto-generated method stub }
If you remove layout. setVisibility(View. GONE); from the code then ft. hide(f); will not hide fragment.
FragmentContainerView is a customized Layout designed specifically for Fragments. It extends FrameLayout , so it can reliably handle Fragment Transactions, and it also has additional features to coordinate with fragment behavior.
Don't mess with the visibility flags of the container - FragmentTransaction.hide/show does that internally for you.
So the correct way to do this is:
FragmentManager fm = getFragmentManager(); fm.beginTransaction() .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out) .show(somefrag) .commit();
OR if you are using android.support.v4.app.Fragment
FragmentManager fm = getSupportFragmentManager(); fm.beginTransaction() .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out) .show(somefrag) .commit();
In addittion, you can do in a Fragment (for example when getting server data failed):
getView().setVisibility(View.GONE);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With