带参数的无头片段,如何使用Fragment.newInstance?

时间:2017-02-09 21:04:44

标签: android android-fragments

我一直在研究3个不同的教程,以获得一个无头片段来打开套接字并在生命周期变化中保持开放。我想我真的很亲密,但有一个最终元素逃脱了我。用于打开套接字和线程的片段的内容是基于一个相当好的类,所以我不太关心那个部分,至少目前是这样。这是片段的相关部分,剩下的就是让它不那么折磨。我要做的是传递p2p组所有者的IP和端口。 (没问题)

public class ConnectionFragment extends Fragment {

    private InetAddress mGoAddress;
    private int mGoPort;
    private Client mClient;
    private static final String TAG = "Connection";
    private static final String CLIENT_TAG = "Client";
    private Server mServer;
    private Socket mSocket;
    private ConnectionFragmentListener mListener;


    public static ConnectionFragment newInstance(InetAddress address, int port){
        Bundle bundle = new Bundle();
        bundle.putSerializable("GoAddress", address);
        bundle.putInt("GoPort", port);
        ConnectionFragment fragment = new ConnectionFragment();
        fragment.setArguments(bundle);

        return fragment;
    }


    private void readBundle(Bundle bundle){
        if (bundle != null){
            mGoAddress = (InetAddress)bundle.getSerializable("GoAddress");
            mGoPort = bundle.getInt("GoPort");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        readBundle(getArguments());
        mGoAddress = (InetAddress) getArguments().getSerializable("GoAddress");
        mGoPort = getArguments().getInt("GoPort");

        mServer = new Server();

    }

然后在我的活动中,我这样做,给它集团所有者IP和端口。

mConnection = ConnectionFragment.newInstance(goInetAddress, prefixedPort);

我的问题是,我该怎么办才能运行mConnection? 谢谢。

1 个答案:

答案 0 :(得分:0)

您必须在创建片段后添加片段。由于它没头,你不需要容器ID:

getSupportFragmentManager()
    .beginTransaction()
    .add(mConnection, TAG)
    .commit();