简体   繁体   English

如何将从CalendarView中选择的日期(默认为当前日期)传递到下一个Activity?

[英]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. 我当前有一个CalendarView活动,我希望用户从CalendarView中选择要传递给下一个片段的日期,从而该日期将显示在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? 我尝试参考此答案: Android CalendarView:如何获取正确格式的日期? and I managed to get the date displayed in LogCat, but it doesn't pass to the fragment. 并且我设法在LogCat中显示了日期,但它没有传递给片段。 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. 如果在MainActivity中保留对Fragment的引用,则可以像与其他任何对象一样与其进行交互。 An example: 一个例子:

MainActivity.java MainActivity.java

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

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

MyFragment.java 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(); 它会返回您的日期,您可以调用第二个活动Date date = get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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