我想将我选择的日期转移到主要活动但是" date"总是空的

时间:2017-08-19 20:36:32

标签: android

这是Calender的代码,我想选择它,它可以发送到mainactivity

public class CalendarActivity extends AppCompatActivity {

private CalendarView calendarView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calendar);
    calendarView=(CalendarView)findViewById(R.id.calendarView);
    calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
            String date=year+"/"+month+1+"/"+dayOfMonth;
            Intent intent=new Intent(CalendarActivity.this,MainActivity.class);
            intent.putExtra("date",date);
            startActivity(intent);
        }
    });
}

}

代码部分:

  String date=getIntent().getStringExtra("date");
    Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();

4 个答案:

答案 0 :(得分:0)

尝试使用bundle:

Bundle extras = new Bundle();
extras.putString("date", date);
intent.putExtra(extras);

MainActivity:

Bundle extras = getIntent().getExtras();
String date = extras.getString("date");

答案 1 :(得分:0)

试试这个:
Long date; date = calendarview.getDate(); 然后将日期传递给其他活动。

答案 2 :(得分:0)

您应该考虑使用Bundle向活动发送信息。你可以做这样的事情

// Make the bundle     
Bundle args = new Bundle();
// Give the bundle a string
args.putString("date", new Gson().toJson(date, Date.class));

现在,您可以从活动中获取捆绑包

@Override
public void onCreate(Bundle savedInstanceState) {
...
// Retrieve sent bundle
Bundle b = this.getIntent().getExtras();

// Try to get the dateSelected that was sent as a string
String dateJson = savedInstanceState.getString("date", "");

// Convert our string to an object
Date date = new Gson().fromJson(dateJson, Date.class);

// Do whatever you want with your date object
// you should also use a SimpleDateFormat to print dates 
Toast.makeText(getApplicationContext(), date, Toast.LENGTH_SHORT).show();
 ...       
}

答案 3 :(得分:0)

试试这个,

在意图中设置日期时,请写下:

String date=year+"/"+month+1+"/"+dayOfMonth;
Intent intent=new Intent(CalendarActivity.this,MainActivity.class);
intent.putStringExtra("date",date);
startActivity(intent);

在下面的另一个活动中写下您希望以字符串格式获取日期:

String date = getIntent().getStringExtra("date");