【问题标题】:Passing data from an Activity to a fragment that has no onCreate将数据从 Activity 传递到没有 onCreate 的片段
【发布时间】:2017-06-08 04:28:13
【问题描述】:

是否可以使用 Bundle 将数据从 Activity 传递到没有 OnCreate 的 Fragment

【问题讨论】:

  • 你可以在片段中实现onCreate:检查这里:developer.android.com/reference/android/app/…
  • fragment 有一个 onCreate() 但您不能从需要事件总线或接口方法的活动中传递数据。
  • 不,不可能
  • 片段中不需要onCreate方法来获取传递的数据。您可以在附加后的任何片段生命周期方法中使用 getArguments() 获取片段中的数据。

标签: android android-fragments android-intent android-bundle


【解决方案1】:

试试这个

public class SampleActivity extends AppCompactActivity {


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

        if (savedInstanceState == null) {
            Fragment fragment = new SampleFragment();

            Bundle args = new Bundle();

            args.putInt("sample_int", 1);

            fragment.setArguments(args);

            getSupportFragmentManager().beginTransaction()
                 .add(R.id.container, fragment)
                 .commit();
        }
    }
}



public class SampleFragment extends Fragment {


    @Override
    public void onResume() {
        Bundle args = getArguments();

        if (args != null) {
            int sampleInt = args.getInt("sample_int", -1);
        }
    }
}

【讨论】:

    【解决方案2】:

    从 Activity 发送数据的意图如下:

    Bundle bundle = new Bundle();
    bundle.putString("edttext", "From Activity");
    // set Fragmentclass Arguments
    Fragmentclass fragobj = new Fragmentclass();
    fragobj.setArguments(bundle);
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多