onClick 中的变量为 null 但 Fragment 的 onCreate 中没有

Variables null inside onClick but not onCreate of Fragment

我正在尝试将一些变量从 activity 传递到片段,然后返回到 activity。在片段的 onCreate 内, getArguments() 不为空,我能够获取变量。但是,在片段的 onClick 内(触发返回到 activity),getArguments() 和我在 onCreate 中检索到的变量为空。

在我的 Activity:

  public void goToFragment() {
    MyFragment myFragment = new MyFragment();
    // create new bundle and put extras
    Bundle myExtras = new Bundle();
    myExtras.putString("firstName", firstName);
    myExtras.putString("lastName", lastName);
    myExtras.putString("favoriteColor", favoriteColor);
    myFragment.setArguments(myExtras);        
    // start the fragment
    getFragmentManager().beginTransaction()
                        .replace(R.id.container, myFragment.newInstance())
                        .add(myFragment, myExtras.toString())
                        .commit();
  }

我的片段:

public class MyFragment extends Fragment implements View.OnClickListener {

    private String firstName;
    private String lastName;
    private String favoriteColor;

    private Button myButton;

    ...

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            firstName = MyFragment.this.getArguments().getString("firstName");
            lastName = MyFragment.this.getArguments().getString("lastName");
            favoriteColor = MyFragment.this.getArguments().getString("favoriteColor");
            Log.d(TAG, "Extras from activity page: firstName = " + firstName + ", lastName = " + lastName + ", favoriteColor = " + favoriteColor);
        } else {
            Log.v(TAG, "getArguments() != null");
        }
    }

    @Override
    public void onViewCreated(final View view, Bundle savedInstanceState) {
        myButton = (Button) view.findViewById(R.id.myButton);
        myButton.setOnClickListener(this);
    }

    ...

    @Override
    public void onClick(View view) {
        Log.d(TAG, "onClick: triggered...");

        // **ISSUE:** my variables are null here even though they were set in the `onCreate`
        Log.d(TAG, "onClick: firstName = " + firstName);
        Log.d(TAG, "onClick: lastName = " + lastName);
        Log.d(TAG, "onClick: favoriteColor = " + favoriteColor);

        // Alternative attempt: get extras
        //if (MyFragment.this.getArguments() != null) {
        //    firstName = getArguments().getString("firstName");
        //    lastName = getArguments().getString("lastName");
        //    favoriteColor = getArguments().getString("favoriteColor");
        //    Log.d(TAG, "Extras getArguments(): firstName = " + firstName + ", lastName = " + lastName + ", favoriteColor = " + favoriteColor);
        //} else {
        //    Log.d(TAG, "getArguments() != null");
        //}

        // initiate intent
        Intent intent = new Intent(getActivity(), MyActivity.class);
        intent.putExtra("firstName", firstName);
        intent.putExtra("lastName", lastName);
        intent.putExtra("favoriteColor", favoriteColor);
        startActivity(intent);
        break;
    }
}

替代尝试:

有谁知道为什么我的变量在 onClick 而不是 onCreate 的片段中为空(以及如何防止这个问题)?

NullPointerException is thrown when an application attempts to use an object reference that has the null value.

更新您的 replace 方法。删除 .add 方法。

.replace(R.id.container, _fragmentOBJ)

结构

FragmentTransaction replace (int containerViewId, Fragment fragment)

然后

Bundle bundle = getArguments();
firstName = bundle.getString("firstName","");

试试这个

getFragmentManager().beginTransaction()
                    .replace(R.id.container, myFragment)
                    .commit();

而不是这个

 getFragmentManager().beginTransaction()
                     .replace(R.id.container, myFragment.newInstance())
                     .add(myFragment, myExtras.toString())
                     .commit();

我在发布的代码中发现了两个问题。

  1. 为什么要同时使用add()replace()。根据您的要求选择任何一种。
  2. 您已使用 new 关键字

    创建了 Fragment 的实例

    MyFragment myFragment = new MyFragment(); 并设置参数。

但在 replace() 调用 myFragment.newInstance()。希望(因为代码未共享)newInstance() 正在创建 Fragment 的另一个实例并且没有为该实例设置参数。这可能会导致片段中出现空参数。