Android 将数据从活动传递到没有onCreate的片段
是否可以将数据从使用Bundle的活动传递到没有OnCreate的片段?试试这个Android 将数据从活动传递到没有onCreate的片段,android,android-fragments,android-intent,android-bundle,Android,Android Fragments,Android Intent,Android Bundle,是否可以将数据从使用Bundle的活动传递到没有OnCreate的片段?试试这个 public class SampleActivity extends AppCompactActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act
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);
}
}
}
在“活动”中,您发送数据的目的是:
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);
}
您可以在fragment中实现onCreate:检查此处:fragment有一个onCreate(),但您不能从需要eventbus或接口方法的活动中传递数据。不,这是不可能的。不需要在fragment中有onCreate方法来获取传递的数据。附加后,您可以在任何片段生命周期方法中使用getArguments()获取片段中的数据。