Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 611
Michal Avatar asked May 09 '13 16:05

Michal


1 Answers

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
like image 161
ianhanniballake Avatar answered Nov 04 '22 23:11

ianhanniballake