gpt4 book ai didi

android - fragment getArguments() 返回 null

转载 作者:IT老高 更新时间:2023-10-28 23:08:46 25 4
gpt4 key购买 nike

我有一个 Fragment,它有一个 TabHost 作为根布局,如下所示...

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<FrameLayout
android:id="@+id/tab_1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

<!-- More FrameLayouts here - each are placeholders for Fragments -->

</FrameLayout>
</LinearLayout>
</TabHost>

为标签内容创建/更新每个Fragment的代码如下...

private void updateTab(String tabId, int placeholder) {
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag(tabId) == null) {
Bundle arguments = new Bundle();
arguments.putInt("current_day", mCurrentTab);
EpgEventListFragment fragment = new EpgEventListFragment();
fragment.setArguments(arguments);

fm.beginTransaction()
.replace(placeholder, new EpgEventListFragment(), tabId)
.commit();
}
}

EpgEventListFragmentonCreate(...) 方法中,然后我尝试获取参数 Bundle 但我总是得到 null 执行以下操作...

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

Bundle arguments = getArguments();
if (arguments == null)
Toast.makeText(getActivity(), "Arguments is NULL", Toast.LENGTH_LONG).show();
else
mCurrentDay = getArguments().getInt("current_day", 0);

...
}

我在这里缺少什么?我也在 onAttach(...) 中尝试了 getArguments() 但我仍然得到空值。我是使用 Fragments 的新手,所以我希望有一个简单的原因,但我在搜索时没有想到任何东西。

最佳答案

我认为这与您的问题有关:

fm.beginTransaction()
.replace(placeholder, new EpgEventListFragment(), tabId)
.commit();

你正在制作一个新的 Fragment(它没有参数,因为它是新实例化的)。

不如试试

Fragment fragment = new EpgEventListFragment();
fragment.setArguments(arguments);
fm.beginTransaction()
.replace(placeholder, fragment, tabId)
.commit();

关于android - fragment getArguments() 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14970790/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com