FragmentTabHost片段适配器在返回选项卡时为空,片段/视图保持不变

时间:2017-01-05 03:54:51

标签: android android-fragments fragment-tab-host

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

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

只有在我为聊天片段初始化适配器时添加了一个制表符更改侦听器后,才会弹出此问题。

请注意,首次初始化选项卡的内容很好,但是当您返回选项卡时,适配器中的内容为空。这意味着在创建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的主要活动(我已经排除了只接受输入并将内容发送到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实例,因为它不会执行任何操作。

1 个答案:

答案 0 :(得分:0)

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

我通过将适配器内容保持为实例变量列表对象来修复此问题,我想在更改适配器时添加或删除字符串。也不要在适配器中放置字符串,更新列表就足够了。该列表将直接将其添加到适配器。

另请注意,如果您在片段外部设置初始内容,则可能不会在首次初始化选项卡时显示。只需要注意你的语句排序以及何时调用。片段建设是时髦的事业。

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