简体   繁体   中英

How to pass date selected from CalendarView (current as default) into next Activity?

I currently have an activity with a CalendarView, I want the user to select the date from the CalendarView to be passed to the next fragment, whereby the date will be displayed in a TextView. I have looked all over, but I have no idea how to extract the date into a string, and then retrieve it again in the fragment the activity will pass the intent to.

I tried to refer to this answer: Android CalendarView: How do I get the date in correct format? and I managed to get the date displayed in LogCat, but it doesn't pass to the fragment. If possible can someone show me how the code can be readjusted to pass it over to the fragment? Thanks yall so much!

If you keep a reference to your Fragment in your MainActivity, you can interact with it just as any other object. An example:

MainActivity.java

MyFragment my_fragment;
...
public void onCreate() {
    ...
    my_fragment = new MyFragment();
    ...
}

public void sendDateToFragment(Calendar date) {
    my_fragment.setDate(date);
}

MyFragment.java

Calendar calendar;
...
public void setDate(Calendar date) {
    // You can choose any type of object to accept,
    // this is just an example.
    calendar = date;
}

Hope this helps.

You can handle it via a Bundle:

public void send(int day, int month, int year){
    Bundle date = new Bundle();
    date.putInt("Day", day);
    date.putInt("Month", month);
    date.putInt("Year", year);
    Intent in=new Intent(Activity.this,SecondActivity.class);
    in.putExtras(date);
    startActivity(in);
}

and in the second activity:

public Date get(){
    Bundle second = getIntent().getExtras();
    return new Date(second.getInt("Year"),
        second.getInt("Month"),second.getInt("Day"));
}

it will return your date and you can call in the second activity Date date = get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM