如何从活动传递参数到片段

时间:2015-03-03 10:32:16

标签: android android-fragments fragment bundle

我有一个活动,通过采用者类实例化和填充片段。我想将值/对象传递给此Fragment采用者类,以便我可以指定布局等。

我尝试使用setArgument方法传递bundle但我的代码却炸毁了,不知道为什么。据我所知,我可以在采用者类的onCreate方法中收集包。我看到在评论代码之后立即正确设置了参数,但是之后它崩溃了,我不明白为什么。如果我删除捆绑代码它不会崩溃。 :(

下面是我的代码,有人知道我应该把捆绑代码放在哪里,注释掉了吗?

public class LoginScreen extends ActionBarActivity {
    private final String ARG_SELECTED_LAYOUT_ID = "selectedLayoutId";
private final int DEFAULT_LAYOUT = R.layout.layout_list;

private int mSelectedLayoutId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowHomeEnabled(false);

    mSelectedLayoutId = DEFAULT_LAYOUT;
    if (savedInstanceState != null) {
        mSelectedLayoutId = savedInstanceState.getInt(ARG_SELECTED_LAYOUT_ID);
    }

    addLayoutTab(
            actionBar, R.layout.layout_list, R.drawable.ic_list, "list");
    addLayoutTab(
            actionBar, R.layout.layout_grid, R.drawable.ic_grid, "grid");
    addLayoutTab(
            actionBar, R.layout.layout_staggered_grid, R.drawable.ic_staggered, "staggered");
    addLayoutTab(
            actionBar, R.layout.layout_spannable_grid, R.drawable.ic_spannable, "spannable");
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(ARG_SELECTED_LAYOUT_ID, mSelectedLayoutId);
}

private void addLayoutTab(ActionBar actionBar, int layoutId, int iconId, String tag) {
    ActionBar.Tab tab = actionBar.newTab()
            .setText("")
            .setIcon(iconId)
            .setTabListener(new TabListener(layoutId, tag));
    actionBar.addTab(tab, layoutId == mSelectedLayoutId);
}

public class TabListener implements ActionBar.TabListener {
    private LayoutFragment mFragment;
    private final int mLayoutId;
    private final String mTag;


    public TabListener(int layoutId, String tag) {
        mLayoutId = layoutId;
        mTag = tag;
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
        mFragment = (LayoutFragment) getSupportFragmentManager().findFragmentByTag(mTag);



        if (mFragment == null) {
            mFragment = (LayoutFragment) LayoutFragment.newInstance(mLayoutId);
            ft.add(R.id.content, mFragment, mTag);

        } else {
            ft.attach(mFragment);
        }


        /*
            Bundle bundle = new Bundle();
            bundle.putInt("noTiles", 4);
            mFragment.setArguments(bundle);           
        */

        mSelectedLayoutId = mFragment.getLayoutId();
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
        if (mFragment != null) {
            ft.detach(mFragment);
        }
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
    }
}

}

logcat的

03-03 11:56:53.675  32507-32507/weebuns.predictionking E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: weebuns.predictionking, PID: 32507
    java.lang.RuntimeException: Unable to start activity ComponentInfo{weebuns.predictionking/weebuns.predictionking.LoginScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void weebuns.predictionking.LayoutFragment.setArguments(android.os.Bundle)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void weebuns.predictionking.LayoutFragment.setArguments(android.os.Bundle)' on a null object reference

5 个答案:

答案 0 :(得分:3)

从活动中您按意图发送数据:

  Bundle bundle = new Bundle();
    bundle.putString("edttext", "From Activity");
    // set Fragmentclass Arguments
    Fragmentclass fragobj = new Fragmentclass();
    fragobj.setArguments(bundle);
    ft.add(R.id.content, fragobj, mTag);

并在Fragment onCreateView方法中:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

答案 1 :(得分:3)

要将参数传递给您的片段,建议您创建一个公共静态方法来实例化您的片段:

public static MyFragment newInstance(String firstArg) {
        MyFragment f = new MyFragment ();
        Bundle args = new Bundle();
        args.putString("ARG1", firstArg);
        f.setArguments(args);
        return f;
    }

然后使用onCreateView()方法检索您的args,如:

String arg = getArguments().getString("ARG1");

使用静态方法在您的其他片段或活动中使用您的参数实现新片段:

MyFragment f = MyFragment.newInstance(myArg);

答案 2 :(得分:1)

如果没有看到logcat,很难说,但肯定你错过了在commit()上调用FragmentTransaction方法。还记得在调用ft.commit()之前设置片段的参数。

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
    mFragment = (LayoutFragment) getSupportFragmentManager().findFragmentByTag(mTag);

    if (mFragment == null) {
        Bundle bundle = new Bundle();
        bundle.putInt("noTiles", 4);
        mFragment = (LayoutFragment) LayoutFragment.newInstance(mLayoutId);
        mFragment.setArguments(bundle);
        //ft.add(R.id.content, mFragment, mTag).commit();
        ft.add(R.id.content, mFragment, mTag);

    } else {
        ft.attach(mFragment);
    }

    mSelectedLayoutId = mFragment.getLayoutId();
}

答案 3 :(得分:1)

在您的活动中

Bundle args = new Bundle();
args.putString("Menu", "Your String");
Fragment detail = new FragmeantOne();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();

在你的片段..在onCreateView()

String menu = getArguments().getString("Menu");
someTextView.setText(menu);

答案 4 :(得分:1)

您可以使用Bundle将数据从活动传输到片段或将数据从片段传输到片段。

Bundle bundle = new Bundle();
DisplayDataList fragment = new DisplayDataList();
bundle.putString("listitem", "Buyer,Seller");
            fragment.setArguments(bundle);

            getFragmentManager().beginTransaction().replace(
                    R.id.frame_container, fragment).addToBackStack(null).commit();

你希望在DisplayDataList Fragment类中接收该捆绑i.w的位置。您必须使用getArguments()方法。

DisplayDataList

 Bundle bundle = getArguments();
            String getdata = bundle.getString("listitem");
            System.out.println("Data got-->>> " + getdata);

希望这会对你有所帮助。