11

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

这是MainActivity.java's 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();
    }
}

HeadlinesFragment.javaonCreate()

@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));

}

我在这里阅读了几篇 QA,比如这个Fragment getArguments() 返回 null,以及许多其他与setArguments()and相关的内容getArguments(),但我仍然被卡住了。

而且我已经将BundleandToast代码移到onAttach()和移到onCreateView()无济于事。我的代码有什么问题?我想我错过了一些东西,但不知道是什么。
请帮忙!谢谢。

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

--------------------------------------
| MainActivity <-> HeadlinesFragment |
|      |                             |
|      |>> ArticlesFragment          |
--------------------------------------

并且HeadlinesFragment在运行时运行。

*这些代码在使用宽度小于 600 像素的 Android 小工具时有效。但是在平板电脑上使用时不起作用(> = 600px),正如下面的@Tesla1984 所证明的那样。但我想要的是在 gadget < 600px 和 gadget > 600px 上的相同结果。

4

4 回答 4

10

@tonny

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

主要活动

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();
    }
}

头条新闻片段

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));
}

这是结果

在此处输入图像描述

于 2013-05-20T04:42:13.230 回答
2

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

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

<fragment>从我的 XML 布局中删除了该元素,它起作用了!

于 2014-06-18T10:41:18.823 回答
1

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

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

让我感到困惑的是fragment.setArguments(getIntent().getExtras());MainActivity.java 的onCreate。他们把代码放在那里,我相信它会起作用,因为它来自Android 官方开发人员指南和 API http://developer.android.com/training/basics/fragments/fragment-ui.html,但它没有工作(现在我相信那段代码不会做任何事情)。因此,任何从那里阅读教程或示例的人,都对它持保留态度!

代码如下,大家可以看懂。

MainActivity.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;
    }
}

标题片段.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.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // The container Activity must implement this interface so the frag can deliver messages
    public interface OnHeadlineSelectedListener {
        /** Called by HeadlinesFragment when a list item is selected */
        public void onArticleSelected(int position);
        public Bundle getBundle();
    }

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

        Bundle bundle = mCallback.getBundle();
        Toast.makeText(getActivity(), "headline fragment " + bundle, Toast.LENGTH_LONG).show();

        // 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;

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

    }

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

        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onStart() {
        super.onStart();

        // When in two-pane layout, set the listview to highlight the selected list item
        // (We do this during onStart because at the point the listview is available.)
        if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception.
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        // Notify the parent activity of selected item
        mCallback.onArticleSelected(position);

        // Set the item as checked to be highlighted when in two-pane layout
        getListView().setItemChecked(position, true);
    }
}
于 2013-05-16T03:01:30.810 回答
0

看起来您正在将一个键和值对插入到您的包中。您可能需要引用键值,如getArguments().getString(category);

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

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

于 2013-05-15T10:15:46.080 回答