第一次看不到Android Fragment Visibility

时间:2014-02-06 21:10:14

标签: android fragment

我需要根据菜单按钮单击使片段可见且不可见。我使用getView.getvisibility来检查它是否可见。它第一次返回0,根据我的条件被认为是可见的并且不显示片段。 我的代码:

LinearLayout menuButton = (LinearLayout)findViewById(R.id.home_button);     
        if(menuButton != null)
        {           
            menuButton.setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {   
                    Fragment navFragment = getSupportFragmentManager().findFragmentById(R.id.nav_list_fragment);
// First time the value of navFragment.getView().getVisibility() is 0
                    if(navFragment.getView().getVisibility() == 8)
                    {
//if visibility value is 8, make the fragment visible
                        navFragment.getView().bringToFront();   
                        navFragment.getView().setVisibility(0);
                    }
                    else
                    {
//if visibility value is 0, make the fragment invisible

                        navFragment.getView().setVisibility(8);
                    }
});
}
}

2 个答案:

答案 0 :(得分:1)

当您为片段扩充布局时,应确保将可见性设置为GONE。视图的默认值(以及您的片段)是可见的。

此外,您应该使用常量View.VISIBLE和View.GONE而不是0,8。

答案 1 :(得分:0)

在on create中将片段添加到视图中,并立即使用hideFragment

隐藏它
   public void hideFragment(Fragment fragment) {
        Log.d(TAG, "hiding fragment");
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.hide(fragment);
        ft.commit();
    }

public void showFragment(Fragment fragment) {
    Log.d(TAG, "showing fragment");
    if (fragment.isAdded() && fragment.isHidden()) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.show(fragment);
        ft.commit();
    }
}

 Fragment navFragment = getSupportFragmentManager().findFragmentById(R.id.nav_list_fragment);//put this outside the click method


menuButton.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {   

                if(fragment.isAdded() && fragment.isHidden()){
                      showFragment(fragment);
                 }
                else
                {
                      hideFragment(fragment);
                }
});