Android Fragment getArguments()返回null

时间:2013-05-15 09:48:01

标签: android android-fragments

正如标题所示 我从这里下载了Fragment代码,http://developer.android.com/shareables/training/FragmentBasics.zip 这是来自 Android官方开发者网站的片段示例。 http://developer.android.com/training/basics/fragments/fragment-ui.html

这是MainActivity.java的{​​{1}}:

onCreate()

/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.news_articles); // Check whether the activity is using the layout version with // the fragment_container FrameLayout. If so, we must add the first fragment if (findViewById(R.id.fragment_container) != null) { // However, if we're being restored from a previous state, // then we don't need to do anything and should return or else // we could end up with overlapping fragments. if (savedInstanceState != null) { return; } // Create an instance of ExampleFragment HeadlinesFragment fragment = new HeadlinesFragment(); // In case this activity was started with special instructions from an Intent, // pass the Intent's extras to the fragment as arguments //fragment.setArguments(getIntent().getExtras()); Bundle args= new Bundle(); args.putString("category", "clothes"); args.putString("item", "shirts"); fragment.setArguments(args); // Add the fragment to the 'fragment_container' FrameLayout getSupportFragmentManager().beginTransaction() .replace(R.id.fragment_container, fragment).commit(); } } 的{​​{1}}:

HeadlinesFragment.java

我在这里阅读了几个质量保证书,例如Fragment getArguments() returns null,以及与onCreate()@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // We need to use a different list item layout for devices older than Honeycomb int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1; Bundle args = getArguments(); if (args == null) { Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show(); } else { Toast.makeText(getActivity(), "text " + args , Toast.LENGTH_LONG).show(); } // Create an array adapter for the list view, using the Ipsum headlines array setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines)); } 相关的许多其他质询,但我仍然被卡住了。

我已将 setArguments() getArguments() 代码移至BundleToast无济于事。我的代码有什么问题?我想我错过了什么,但不知道它是什么 请帮忙!感谢。

修改
我会更清楚地表明我的意图。在我下载的FragmentBasic中,有MainActivity.java,HeadlinesFragment.java和ArticlesFragment.java。从MainActivity.java到ArticlesFragment.java的“通信”不是问题。我想要的是将数据从MainActivity.java发送到HeadlinesFragment.java。他们的联系是这样的:

onAttach()

onCreateView()正在运行时运行。

*当使用带有&lt;的Android小工具时,这些代码可以正常工作600px宽度。但是在平板电脑上使用时不起作用(&gt; = 600px),正如下面@ Tesla1984所证明的那样。但我想要的是小工具&lt; 600px和小工具&gt; 600px的。

4 个答案:

答案 0 :(得分:7)

@tonny

我已经下载了FragmentBasics.zip。我只更改参数名称。代码和结果图片。

<强> MainActivity

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create an instance of ExampleFragment
        HeadlinesFragment fragment = new HeadlinesFragment();

        // In case this activity was started with special instructions from an Intent,
        // pass the Intent's extras to the fragment as arguments
//            firstFragment.setArguments(getIntent().getExtras());
        //test
        Bundle args= new Bundle();
        args.putString("category", "clothes");
        args.putString("item", "shirts");
        fragment.setArguments(args);

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragment_container, fragment).commit();
    }
}

<强> HeadlinesFragment

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

    // We need to use a different list item layout for devices older than Honeycomb
    int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ?
            android.R.layout.simple_list_item_activated_1 : android.R.layout.simple_list_item_1;

    Bundle args = getArguments();
    if (args == null) {
        Toast.makeText(getActivity(), "arguments is null " , Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getActivity(), "text " + args , Toast.LENGTH_LONG).show();
    }    

    // Create an array adapter for the list view, using the Ipsum headlines array
    setListAdapter(new ArrayAdapter<String>(getActivity(), layout, Ipsum.Headlines));
}

这是结果

enter image description here

答案 1 :(得分:3)

我有同样的问题,但解决了它:)

我的问题是我在Activity的XML布局中有<fragment android:name="">元素。因此,片段的onCreate()在Java代码中的调用之前被调用,因此不会设置参数。

我从XML布局中删除了<fragment>元素并且它有效!

答案 2 :(得分:1)

我已经解决了。看起来从MainActivity.java向HeadlinesFragment.java发送数据的唯一方法是来自回调(如果有其他人知道其他方式,请做出贡献,那么我们还有其他方法可以帮助其他人解决这类问题)。

主要代码来自MainActivity.java的函数public Bundle getBundle() {},然后在HeadlinesFragment.java上设置interface部分,并添加public Bundle getBundle();,最后,从HeadlinesFragment.java {调用它{ {1}}。

在MainActivity.java的onCreate上,fragment.setArguments(getIntent().getExtras());让我感到困惑。他们把那些代码放在那里,我相信它会起作用,因为它来自 Android官方开发人员指南和API http://developer.android.com/training/basics/fragments/fragment-ui.html,但它没有用(现在我相信这段代码赢了'做任何事情)。因此,任何从那里阅读教程或样本的人都会带着一丝盐!

下面的代码,所以每个人都可以理解它。

<强> MainActivity.java

onCreate

<强> HeadlinesFragment.java

    /*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.example.android.fragments;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;

public class MainActivity extends FragmentActivity 
        implements HeadlinesFragment.OnHeadlineSelectedListener {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_articles);

        // Check whether the activity is using the layout version with
        // the fragment_container FrameLayout. If so, we must add the first fragment
        if (findViewById(R.id.fragment_container) != null) {

            // However, if we're being restored from a previous state,
            // then we don't need to do anything and should return or else
            // we could end up with overlapping fragments.
            if (savedInstanceState != null) {
                return;
            }

            Toast.makeText(getApplicationContext(), "activity", Toast.LENGTH_LONG).show();

            // Create an instance of ExampleFragment
            HeadlinesFragment fragment = new HeadlinesFragment();

            // In case this activity was started with special instructions from an Intent,
            // pass the Intent's extras to the fragment as arguments
            fragment.setArguments(getIntent().getExtras());

            // Add the fragment to the 'fragment_container' FrameLayout
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_container, fragment).commit();
        }
    }

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment

        // Capture the article fragment from the activity layout
        ArticleFragment articleFrag = (ArticleFragment)
                getSupportFragmentManager().findFragmentById(R.id.article_fragment);

        if (articleFrag != null) {
            // If article frag is available, we're in two-pane layout...

            // Call a method in the ArticleFragment to update its content
            articleFrag.updateArticleView(position);

        } else {
            // If the frag is not available, we're in the one-pane layout and must swap frags...

            // Create fragment and give it an argument for the selected article
            ArticleFragment newFragment = new ArticleFragment();
            Bundle args = new Bundle();
            args.putInt(ArticleFragment.ARG_POSITION, position);
            newFragment.setArguments(args);
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack so the user can navigate back
            transaction.replace(R.id.fragment_container, newFragment);
            transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
    }

    public Bundle getBundle() {
        Bundle args = new Bundle();
        args.putString("category", "cloths");
        args.putString("item", "shirts");
        return args;
    }
}

答案 3 :(得分:0)

看起来您正在将密钥和值对插入到捆绑包中。您可能需要像getArguments().getString(category);

中那样引用键值

根据putString的文档:将String值插入此Bundle的映射中,替换给定键的任何现有值。键或值可以为null。

参数 key一个String,或null value一个String,或null