繁体   English   中英

如何从另一个片段打开片段

[英]How to open a fragment from another fragment

我有一个标签式活动,其中有三个标签。 主选项卡是主选项卡,它包含一个按钮。 我的问题是如何在按下按钮并将其保持在相同的选项卡活动后打开一个新片段? 这是我的Home选项卡类代码:

import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
/**
 * Created by user-pc on 15/01/2017.
 */


public class Home extends Fragment {
    private boolean flag;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.hometab, container, false);
        final Button RestButton = (Button) rootView.findViewById(R.id.RestButton);
        final Button ShopButton = (Button) rootView.findViewById(R.id.ShopButton);
        final Button HangoutButton = (Button) rootView.findViewById(R.id.HangoutButton);
        RestButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        return rootView;
    }
}

当您在android中添加默认选项卡式活动时,您将获得一个活动,该活动使用ViewPager作为FragmentPagerAdapter管理的片段的容器。

来自FragmentPagerAdapter的文档

此版本的寻呼机最适合在有少量通常更多静态片段进行分页时使用,例如一组选项卡。

如果我理解正确的话,你想要一个片段,即Home片段,它驻留在一个页面中(让我们称之为Page1)与另一个片段动态交换(让我们调用这个新片段FragmentB)并保持为新的片段,如果你切换到另一个页面(让我们称之为Page2)并返回到它的页面(意味着当切换回Page1时你会看到FragmentB)。

为此,您最好使用FragmentStatePagerAdapter 在Page1的片段内 - 有一个容器用于另一个片段(片段中的片段),占据父片段的整个区域。 其中的第一个和默认片段是Home片段,如果之前没有保存状态,它将在onCreateView方法中动态加载。 否则 - 加载的片段将根据保存的状态 - 甚至直接从保存的状态。 要拥有该已保存的状态 - 您需要实现onSaveInstanceState(Buncle)以获得已保存的状态。 然后将Home片段与FragmentB交换到容器片段内,该容器片段每次都加载到Page1中 - 但它会记住最后加载到哪个片段 - 并且可以正确地恢复它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM