在XML布局中定义的android:visibility片段

9
这是如何运作的?我有以下布局:

该怎么做呢?我有以下布局:

<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>

请注意第二个片段具有android:visibility="gone",实际上在屏幕上看不见。但是这段代码:
boolean bothVisible = firstFrag.isVisible() && secondFrag.isVisible();

返回true,这并不是我预期的结果。我想知道是否使用 android:visibility 是正确的,因为我在文档中找不到任何相关信息。


你是否正确地初始化(获取引用)firstFragsecondFrag - zbr
是的,我通过 getFragmentById() 获取引用。 - Michal
像这样 firstFrag = getFragmentManager().findFragmentById(R.id.search_form_fragment);secondFrag = setFragmentManager().findFragmentById(R.id.result_list_fragment); - zbr
是的,这就是我获取Fragment引用的方式。 - Michal
好的,那我也不知道了。我只是想让你确认一下代码中没有什么愚蠢的错误。祝你好运。 - zbr
2个回答

7

根据Fragment源代码isVisible的定义如下:

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

即它附加到活动中,它不是通过 FragmentTransaction.hide 隐藏的,视图已被膨胀,视图已附加到窗口,并且 片段的内部视图View.VISIBLE

我认为问题在于为了膨胀您的片段,系统创建了一个布局来容纳片段的视图。你设置的是该视图为 View.GONE,而不是片段创建的内部视图。

我建议将您的条件更改为:

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

0

我尝试过这样做

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"/>

代码

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

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

我的日志记录如下:

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

来自 Android 文档,isVisible() 如果片段当前对用户可见,则返回 true。这意味着它:(1) 已添加,(2) 其视图已附加到窗口,并且 (3) 未隐藏。

也许您还没有添加该片段?从代码中我无法判断。希望这可以帮助您。


3
好的,但您在程序中添加碎片。我想知道在XML的<fragment>标签上如何使用android:visibility。 - Michal
我认为ianhanniballake的回答就是你要找的。 - Ende Neu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接