将数据从Activity传递到没有onCreate的片段

时间:2017-06-08 04:28:13

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

是否可以将使用Bundle的Activity中的数据传递给没有OnCreate的片段

2 个答案:

答案 0 :(得分:2)

试试这个

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

答案 1 :(得分:0)

从“活动”中,您可以按意图发送数据:

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