安卓:getArguments() 总是返回 null 值

3

我是Android开发新手,最近遇到了一个问题。我的Fragment无法从Activity中获取参数。以下是我的活动代码。

private void CountUnreadNotifications() {
        Cursor unread = db.getUnread();
        Bundle bundle = new Bundle();
        String number = Integer.toString(unread.getCount());
        bundle.putString("noOfNotif", number);
        BottomFragment fragment = new BottomFragment();
        fragment.setArguments(bundle);
    }

我确定变量number不为空。以下是我的片段代码。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        String i = null;
        Bundle bundle = this.getArguments();
        if(bundle != null){
            i = bundle.getString("noOfNotif");
        }
        else {
             i = "0";
        }

        View view = inflater.inflate(R.layout.fragment_menu_page, container,
                false);

        txtnoNotif = (TextView) view.findViewById(R.id.txtnoNotif);     
        txtnoNotif.setText(i);

请问有人可以帮助我回答这个问题吗?谢谢。 以下是我的Activity Oncreate中的代码。
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu_page);

        mDB.Open();
        CountUnreadNotifications();
        viewFragment();

    }

查看Fragment方法。

private void viewFragment() {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        BottomFragment myFragment = new BottomFragment();
        ft.add(R.id.linearLayout, myFragment);
        ft.commit();
    }

你希望在Fragment/TextView中看到什么?我的意思是,如果“noOfNotif”计数也为零,使用值“0”作为默认值可能会有点令人困惑。 - harism
我正在尝试在片段中的Textview中放置一个值。我确定计数不为零。 - user3055923
我明白了。你的CountUnreadNotifications方法怎么样?你似乎正确地实例化了BottomFragment,但我没有看到它在任何地方被使用或返回。你确定你所做的FragmentTransaction实际上是添加/替换了这个特定的BottomFragment实例吗? - harism
对不起。好的。我会更新问题。 - user3055923
什么是viewFragment()? - Lazy Ninja
显示剩余3条评论
1个回答

2

您的CountUnreadNotifications()方法并不完整。
请按以下方式更改,并注释掉viewFragment()

private void CountUnreadNotifications() {
    Cursor unread = db.getUnread();
    Bundle bundle = new Bundle();
    String number = Integer.toString(unread.getCount());
    bundle.putString("noOfNotif", number);
    BottomFragment fragment = new BottomFragment();
    fragment.setArguments(bundle);
    FragmentTransaction trans = mManager.beginTransaction();
    trans.replace(R.id.fragment_container, fragment ); // change fragment_container to your container
    trans.commit(); 

    }

我猜你正在尝试在方法viewFragment()中转换到BottomFragment,其中你必须再次初始化BottomFragment fragment = new BottomFragment();,从而丢失你的参数。
请发布viewFragment();


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接