Michal
Michal

Reputation: 2084

Fragment android:visibility in xml layout definition

How does it works? I have layout like below:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/search_form_fragment"
        android:name="FragmentClass"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <fragment
        android:id="@+id/result_list_fragment"
        android:name="FragmentClass"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />
</LinearLayout>

Note the second fragment has android:visibility="gone" and indeed it is not visible on screen. But this code:

boolean bothVisible = firstFrag.isVisible() && secondFrag.isVisible();

returns true, which was not expected by me. I wonder if using android:visibility is correct cause I could not find any information about it in documentation.

Upvotes: 9

Views: 14750

Answers (2)

ianhanniballake
ianhanniballake

Reputation: 199880

Per the Fragment source, isVisible is defined as:

 final public boolean isVisible() {
    return isAdded() && !isHidden() && mView != null
            && mView.getWindowToken() != null && 
               mView.getVisibility() == View.VISIBLE;
}

I.e., it is attached to the activity, it is not hidden (via the FragmentTransaction.hide), the view is inflated, the view is attached to a window, and the interior view of the Fragment is View.VISIBLE.

I believe the issue is that in order to inflate your fragment, the system creates a layout to hold the Fragment's view. It is that view that you are setting to View.GONE, not the interior view that the Fragment creates.

I might suggest changing your condition to be:

findViewById(R.id.result_list_fragment).getVisibility() == View.VISIBLE

Upvotes: 7

Ende Neu
Ende Neu

Reputation: 15783

I tried doing this

XML

<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lateral_login_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone"/>

Code

LoginFrag = LoginFragment.newIstance();     
FragmentTransaction LoginTransaction = fm.beginTransaction();
LoginTransaction.replace(R.id.lateral_login_frame, LoginFrag);
LoginTransaction.commit();

Log.d("visibility", String.valueOf(LoginFrag.isVisible()));

And my log was:

05-09 19:07:54.236: D/visibility(3483): false

From android documentation, isVisible() Return true if the fragment is currently visible to the user. This means it: (1) has been added, (2) has its view attached to the window, and (3) is not hidden.

Maybe you haven't added the fragment just yet? from the code I can't tell. Hope this helps.

Upvotes: 0

Related Questions