在android中显示隐藏片段 [英] Show hide fragment in android

查看:23
本文介绍了在android中显示隐藏片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发包含 2 个片段的应用程序,我想根据需要显示隐藏.以下代码有我的问题的简单示例.这个简单的 Fragmentactivity 包含 1 个按钮和一个列表片段.

I am developing application which contains 2 fragments and i want to show hide according to my need. Following code has simple example of my problem. This simple Fragmentactivity contains 1 button and one listfragment.

这个简单的例子完美无缺.但我对显示隐藏片段不满意.如果删除 layout.setVisibility(View.GONE);从代码然后 ft.hide(f);不会隐藏片段.事实上,我们不是在隐藏片段,而是在隐藏容器.

This simple example works flawless. but i am not satisfied with show hide fragment. If you remove layout.setVisibility(View.GONE); from the code then ft.hide(f); will not hide fragment. In fact we are not hiding fragment we are hiding container.

我的问题是,这是一种显示隐藏片段的方式吗?如果没有,请用经过测试的示例解释如何隐藏和显示片段,因为很多人都面临这个问题.

My Question is, IS this a way to show hide fragments? If not then please explain with tested example How to hide and show Fragments because lots of people are facing this problem.

 public class MainActivity extends FragmentActivity implements OnClickListener {

        Fragment1 f;
        Button b;
        LinearLayout layout;
        Fragment myf;
        @Override
        public void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            b = (Button) findViewById(R.id.button1);
            layout = (LinearLayout) findViewById(R.id.ll);
            f = new Fragment1();
        }

        @Override
        public void onClick(View v) {

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);

            if (f.isHidden()) {
                ft.show(f);
                layout.setVisibility(View.VISIBLE);
                b.setText("Hide");
            } else {
                ft.hide(f);
                b.setText("Show");
                layout.setVisibility(View.GONE);
            }
            ft.commit();
            // TODO Auto-generated method stub
        }

推荐答案

不要弄乱容器的可见性标志 - FragmentTransaction.hide/show 会在内部为您做到这一点.

Don't mess with the visibility flags of the container - FragmentTransaction.hide/show does that internally for you.

所以正确的做法是:

FragmentManager fm = getFragmentManager();
fm.beginTransaction()
          .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
          .show(somefrag)
          .commit();

<小时>

或者如果您使用的是 android.support.v4.app.Fragment

 FragmentManager fm = getSupportFragmentManager();
 fm.beginTransaction()
          .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
          .show(somefrag)
          .commit();

这篇关于在android中显示隐藏片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆