Fragment Hide and show on click
<p>I have a fragment that needs to be updated from the activity continuously and I only want to show this fragment when I click on a button,on click of the same button the fragment should be hidden but still be active so I can update contents of the fragment from the activity (the fragment contains a recycler view).
While hiding and showing this fragment I would like to animate the transaction.</p>

<p>**</p>

<h2>Working Code</h2>

<p>**</p>

<p>Activity XML (the frame layout that contains the fragment)</p>

<pre><code>&lt;FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"&gt;

    &lt;android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/&gt;

    &lt;fragment
            android:name="octave.foodster.fragment_cart"
            android:id="@+id/fragment_cart"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/&gt;

&lt;/FrameLayout&gt;
</code></pre>

<p>The java code in the activity (i removed the animation for now)</p>

<pre><code>        @Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
        case R.id.cart:
            Log.i("click", "menu");

            showHideFragment(fragment);
            break;
    }
    return super.onOptionsItemSelected(item);
}

public void showHideFragment(final Fragment fragment) {

    final FragmentTransaction fragTransaction = getSupportFragmentManager().beginTransaction();
    fragTransaction.setCustomAnimations(R.anim.fragment_slide_from_right, R.anim.animation_leave);

    if (fragment.isHidden()) {
        fragTransaction.show(fragment);
        Log.d("hidden", "Show");
    } else {
        fragTransaction.hide(fragment);
        Log.d("Shown", "Hide");
    }

    fragTransaction.commit();
}
</code></pre>

<p>And in the activities onCreate()--this is done to hide the fragment by default</p>

<pre><code>fragmentManager = getSupportFragmentManager();
    fragment = fragmentManager.findFragmentById(R.id.fragment_cart);
    final FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.hide(fragment);
    fragmentTransaction.commit();
</code></pre>