我试图在Android上创建简单日历,当我尝试从MainActivity向参数为0的另一个Acvitity发送参数(日期,月份,年份)时,我遇到了问题
MainActivity.java
public void onClick(View view) {
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView calendarView, int i, int i1, int i2) {
Bundle localBundle = new Bundle();
localBundle.putInt("Date", i2);
localBundle.putInt("Month", i1);
localBundle.putInt("Year", i);
}
});
if(view == buttonGetDate1) {
Bundle localBundle = new Bundle();
Intent localIntent = new Intent(MainActivity.this, TestActivity.class);
localIntent.putExtras(localBundle);
startActivity(localIntent);
finish();
}
}
TestAcvitity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
datedisplay1 = (TextView) findViewById(R.id.date_display1);
datedisplay1.setText("Date: ");
buttonBack1 = (Button) findViewById(R.id.buttonBack);
buttonBack1.setOnClickListener(this);
Bundle intent = getIntent().getExtras();
int day = intent.getInt("date");
int month = intent.getInt("month");
int year = intent.getInt("year");
Log.d(TAG, "THIRD LOG : " + day + " / " + month + " / " + year);
datedisplay1.setText("Date: " + day + " / " + month + " / " + year);
}
我怎么能解决它? PS。对不起我的英语能力差。
编辑:我尝试调试日志后 EDIT2:更新了TestActivity
in this pic, intent have value are Date = 30 Year = 2017 Month = 4 but it's show null on application
答案 0 :(得分:1)
数据变空,因为您再次点击再次初始化捆绑包,我已经对您的代码进行了一些更改,只是试一试
{
//inside your activity on create scope
int dateData=0;
int monthData=0;
int yearData=0;
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView calendarView, int i, int i1, int i2) {
dateData= i2;
monthData= i1;
yearData= i;
//Log here whether u getting date here?
}
});
public void onClick(View view) {
if(view == buttonGetDate1) {
Bundle localBundle = new Bundle();
localBundle.putInt("Date", dateData);
localBundle.putInt("Month", monthData);
localBundle.putInt("Year", yearData);
Intent localIntent = new Intent(MainActivity.this, TestActivity.class);
localIntent.putExtras(localBundle);
startActivity(localIntent);
finish();
}
}
}//Activity scope ends
TestAcvitity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
datedisplay1 = (TextView) findViewById(R.id.date_display1);
datedisplay1.setText("Date: ");
buttonBack1 = (Button) findViewById(R.id.buttonBack);
buttonBack1.setOnClickListener(this);
Bundle intent = getIntent().getExtras();
int day = intent.getInt("Date");
int month = intent.getInt("Month");
int year = intent.getInt("Year");
Log.d(TAG, "THIRD LOG : " + day + " / " + month + " / " + year);
datedisplay1.setText("Date: " + day + " / " + month + " / " + year);
}
希望这会对你有所帮助。