FragmentTabHost 片段适配器在返回选项卡时为空,Fragment/Views 保留

FragmentTabHost Fragment Adapters Are Empty Upon Returning To Tab, Fragment/Views Remain

我发现了几个与此相关的问题,none 其中对我有帮助。每个问题都与我未在片段中实现的其他函数和视图相关,问题不在于我需要将获取 FragmentManager 的方法交换为片段中任何位置的 getChildFragmentManager(),因为我不需要获取那里有 FragmentManager。

我猜我的问题源于片段而不是主要 activity 中的 FragmentTabHost,但我不太确定。完全没有。我所知道的是,当您在选项卡之间翻页时,适配器内容会消失,但片段本身不会消失。所有视图仍然可用,因此每个片段的功能都保持不变。

仅在我为何时为我的聊天片段初始化适配器添加了选项卡更改侦听器后才会出现此问题。

请注意,选项卡的内容在第一次初始化时没有问题,但是当您 return 到选项卡时,适配器中的内容为空。这意味着创建 FragmentTabHost 时尚未初始化的选项卡,隐藏的选项卡尚未初始化,因此它们在您第一次翻页时仍然有效。

通过调试,我发现这个问题发生在转换发生时,所有适配器在使用会话期间都将保持为空。我在 tabHost.setOnTabChangedListener 调用的初始检查之前放置了这段代码:

//Before paging back to an initialized tab for the first time, the adapters of the initialized tab is populated.
Log.d("test", "pre");
new Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        //At this point, the adapter is empty.
        Log.d("test", "post");
    }
}, 50);

两个片段如下:

public class GroupTasksFragment extends Fragment {

public ArrayAdapter<String> adapter;
private Context context;
public ListView taskListView;

public GroupTasksFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_group_tasks, container, false);
    taskListView = (ListView) rootView.findViewById(R.id.tasksList);
    adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, new ArrayList<String>());
    taskListView.setAdapter(adapter);
    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context = context;
}

@Override
public void onDetach() {
    super.onDetach();
}
}

public class GroupChatFragment extends Fragment{

public ArrayAdapter<String> adapter;
private Context context;
public ListView chatListView;

public GroupChatFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_group_chat, container, false);
    chatListView = (ListView) rootView.findViewById(R.id.chatList);
    adapter = new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, new ArrayList<String>());
    chatListView.setAdapter(adapter);
    return rootView;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context = context;
}

@Override
public void onDetach() {
    super.onDetach();
}
}

FragmentTabHost 的主要 activity(我已经排除了只接受输入并将内容发送到 PubNub 的方法):

public class GroupContentActivity extends AppCompatActivity {

private GroupChatFragment chatFrag;
private GroupTasksFragment taskFrag;
private FragmentTabHost tabHost;
private PubNub connection;
private String groupName;
private String nickName;
private boolean chatFragInitialized = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_group_content);
    tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
    tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);

    tabHost.addTab(tabHost.newTabSpec("tasks").setIndicator("Tasks"),
            GroupTasksFragment.class, null);

    tabHost.addTab(tabHost.newTabSpec("chat")
            .setIndicator("Chat"), GroupChatFragment.class, null);

    groupName = getIntent().getStringExtra("groupName");
    nickName = getIntent().getStringExtra("nickName");
    PNConfiguration config = new PNConfiguration();
    config.setPublishKey(Constants.publishKey);
    config.setSubscribeKey(Constants.subscribeKey);
    connection = new PubNub(config);



    tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            if (!chatFragInitialized && tabId.equals("chat")) {
                chatFragInitialized = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        chatFrag = (GroupChatFragment) getSupportFragmentManager().findFragmentByTag("chat");
                        connection.history()
                                .channel(groupName)
                                .count(50)
                                .async(new PNCallback<PNHistoryResult>() {
                                    @Override
                                    public void onResponse(PNHistoryResult result, PNStatus status) {
                                        for (PNHistoryItemResult item : result.getMessages()) {
                                            final String[] sForm = item.getEntry().getAsString().split(">>>>");
                                            String m = "";
                                            if (sForm.length > 2) {
                                                for (int x = 1; x < sForm.length; x++) {
                                                    m += sForm[x];
                                                }
                                            } else {
                                                m = sForm[1];
                                            }

                                            final String mCopy = m;

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    switch (sForm[0]) {
                                                        case "groupCreated":
                                                            chatFrag.adapter.clear();
                                                            break;
                                                        case "chat":
                                                            chatFrag.adapter.add(mCopy);
                                                    }
                                                }
                                            });

                                        }
                                    }
                                });
                    }
                }, 50);
            }
        }
    });

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            taskFrag = (GroupTasksFragment) getSupportFragmentManager().findFragmentByTag("tasks");

            connection.history()
                    .channel(groupName)
                    .count(50)
                    .async(new PNCallback<PNHistoryResult>() {
                        @Override
                        public void onResponse(PNHistoryResult result, PNStatus status) {
                            for (PNHistoryItemResult item : result.getMessages()) {
                                final String[] sForm = item.getEntry().getAsString().split(">>>>");
                                String m = "";
                                if (sForm.length > 2) {
                                    for (int x = 1; x < sForm.length; x++) {
                                        m += sForm[x];
                                    }
                                } else {
                                    m = sForm[1];
                                }

                                final String mCopy = m;

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        switch (sForm[0]) {
                                            case "addTask":
                                                if (taskFrag.adapter.getPosition(mCopy) < 0) {
                                                    taskFrag.adapter.add(mCopy);
                                                }
                                                break;
                                            case "deleteTask":
                                                if (taskFrag.adapter.getPosition(mCopy) >= 0) {
                                                    taskFrag.adapter.remove(mCopy);
                                                }
                                                break;
                                            case "groupCreated":
                                                taskFrag.adapter.clear();
                                                break;
                                        }
                                    }
                                });

                            }
                        }
                    });

            connection.addListener(new SubscribeCallback() {
                @Override
                public void status(PubNub pubnub, PNStatus status) {
                    if (status.getCategory() == PNStatusCategory.PNUnexpectedDisconnectCategory) {
                        Toast.makeText(getApplicationContext(), "You were disconnected!", Toast.LENGTH_SHORT).show();
                    } else if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                        if (status.getCategory() == PNStatusCategory.PNConnectedCategory) {
                            pubnub.publish().channel(groupName).message("chat>>>><ADMIN> User '" + nickName + "' Connected").async(new PNCallback<PNPublishResult>() {
                                @Override
                                public void onResponse(PNPublishResult result, PNStatus status) {
                                }
                            });
                        }
                    } else if (status.getCategory() == PNStatusCategory.PNReconnectedCategory) {
                        Toast.makeText(getApplicationContext(), "You were reconnected!", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void message(PubNub pubnub, PNMessageResult message) {
                    final String[] sForm = message.getMessage().getAsString().split(">>>>");
                    String m = "";
                    if (sForm.length > 2) {
                        for (int x = 1; x < sForm.length; x++) {
                            m += sForm[x];
                        }
                    } else {
                        m = sForm[1];
                    }

                    final String mCopy = m;

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            switch (sForm[0]) {
                                case "chat":
                                    if (chatFragInitialized) {
                                        chatFrag.adapter.add(mCopy);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                chatFrag.chatListView.setSelection(chatFrag.adapter.getCount() - 1);
                                            }
                                        });
                                    }
                                    break;
                                case "addTask":
                                    taskFrag.adapter.add(mCopy);
                                    connection.publish().channel(groupName).message("chat>>>><ADMIN> Task '" + mCopy + "' added.").async(new PNCallback<PNPublishResult>() {
                                        @Override
                                        public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
                                        }
                                    });
                                    break;
                                case "deleteTask":
                                    taskFrag.adapter.remove(mCopy);
                                    connection.publish().channel(groupName).message("chat>>>><ADMIN> Task '" + mCopy + "' deleted.").async(new PNCallback<PNPublishResult>() {
                                        @Override
                                        public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
                                        }
                                    });
                                    break;
                            }
                        }
                    });
                }

                @Override
                public void presence(PubNub pubnub, PNPresenceEventResult presence) {
                }
            });
            connection.subscribe().channels(java.util.Collections.singletonList(groupName)).execute();
        }
    }, 100);
}

@Override
public void onDestroy(){
    super.onDestroy();
    connection.publish().channel(groupName).message("chat>>>><ADMIN> User '" + nickName + "' Logged Out.").async(new PNCallback<PNPublishResult>() {
        @Override
        public void onResponse(PNPublishResult pnPublishResult, PNStatus pnStatus) {
        }
    });
    connection.disconnect();
    Toast.makeText(getApplicationContext(), "Logged out", Toast.LENGTH_SHORT).show();
}

//More Methods
}

另请注意,问题不在于我需要存储 FragmentManager 实例,因为它不会执行任何操作。

我发现了我的问题。事实证明,每次在 FragmentTabHost 中分页到一个片段时,它的 createView 方法都会被再次调用,并且只调用那个方法,所以通过将片段中的适配器设置为那个视图中的空,我认为这只是在开始时,我每次都重置适配器。

我通过将适配器内容保留为实例变量列表对象来解决此问题,当我想更改适配器时,我会添加或删除字符串 to/from。不要同时将字符串放入适配器中,更新列表就足够了。该列表将直接将其添加到适配器中。

另请注意,如果您在片段之外设置初始内容,则在首次初始化选项卡时可能不会显示。请注意您的语句顺序和调用时间。片段构造是时髦的事情。

然后,每次调用 createView 方法时,我都会将适配器设置为列表中的任何内容。