java 将值/日期从活动传递到片段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 将值/日期从活动传递到片段相关的知识,希望对你有一定的参考价值。

FragmentTransaction ft =  getActivity().getSupportFragmentManager().beginTransaction();
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
Fragment2 fragment2 = new Fragment2();

Bundle bundle = new Bundle();
YourObj obj = SET_YOUR_OBJECT_HERE;
bundle.putSerializable("your_obj", obj);
fragment2.setArguments(bundle);
ft.replace(android.R.id.content, fragment2);
ft.addToBackStack(null);
ft.commit();


//fragment two
Bundle bundle = getArguments();
YourObj obj= (YourObj) bundle.getSerializable("your_obj");
//in activity

Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass(); // fragment name
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();

//in fragment
Bundle bundle = this.getArguments();
String myValue = bundle.getString("message");
// add annotation to model
@SuppressWarnings("serial")
public class HomeScreenViewModel implements Serializable {
    private Boolean isRaceCardAvailable;
    public Integer meetingNumber;
    public Object notificationMessage;
    public Boolean notification;

    public Integer getMeetingNumber() {
        return meetingNumber;
    }

    public void setMeetingNumber(Integer meetingNumber) {
        this.meetingNumber = meetingNumber;
    }

    public Object getNotificationMessage() {
        return notificationMessage;
    }

    public void setNotificationMessage(Object notificationMessage) {
        this.notificationMessage = notificationMessage;
    }

    public Boolean getNotification() {
        return notification;
    }

    public void setNotification(Boolean notification) {
        this.notification = notification;
    }

    public Boolean getIsRaceCardAvailable() {
        return isRaceCardAvailable;
    }

    public void setIsRaceCardAvailable(Boolean isRaceCardAvailable) {
        this.isRaceCardAvailable = isRaceCardAvailable;
    }
}


//in java class
HomeScreenViewModel home = new HomeScreenViewModel();
private void NavigateToMainActivity(HomeScreenViewModel home) {
      Intent i = new Intent(SplashScreen.this, MainActivity.class);
      i.putExtra("HomeScreenDetails",  home);
      startActivity(i);
  }
  
  
// in main activity to receive data
Intent i = getIntent();
home = (HomeScreenViewModel)i.getSerializableExtra("HomeScreenDetails");
NavigateToFragment(home);

以上是关于java 将值/日期从活动传递到片段的主要内容,如果未能解决你的问题,请参考以下文章

如何将值从一个活动中的片段传递到另一个活动? [复制]

如何将值从其他活动传递给 viewpager 片段?

Android Java将变量从片段传递到活动[重复]

如何将值从一个片段的回收器视图项传递到另一个片段

如何将变量从 Activity 传递到 Fragment,并将其传回?

如何将变量从活动传递到片段不能解决以前的所有问题