这里我有一个片段中的日历,我希望在点击日期时,我们会发送一个带有日期(我们点击的日期)的新活动。 那么当我点击日历日期时,如何在新活动中发送日期? 现在,我有这个
import android.icu.util.Calendar;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.CalendarView;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.ButterKnife;
public class Tab2Calendrier extends Fragment {
@Bind(R.id.calendar)
CalendarView calendar;
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2calendrier, container, false);
ButterKnife.bind(this, rootView);
calendar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
@Override
public void onGlobalLayout()
{
}
});
return rootView;
}
}
由于
答案 0 :(得分:0)
您应该使用setOnDateChangeListener()
。所以代码可以是这样的:
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab2calendrier, container, false);
ButterKnife.bind(this, rootView);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
Intent intent = new Intent(getActivity(), MyActivity.class);
// Save the selected date in for using in the new activity
intent.putExtra("year", year);
intent.putExtra("month", month);
intent.putExtra("dayOfMonth", dayOfMonth);
startActivity(intent);
}
});
return rootView;
}
你的MyActivity类应该是这样的:
class MyActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
Intent intent = getIntent();
if (intent != null) {
// You can check for null to make sure
int year = intent.getIntExtra("year", 2017);
int month = intent.getIntExtra("month", 1);
int dayOfMonth = intent.getIntExtra("dayOfMonth", 1);
// Use these to put them inside a TextView...
}
}
}
答案 1 :(得分:0)
看这里https://developer.android.com/reference/android/widget/CalendarView.OnDateChangeListener.html
calendar.setOnDateChangeListener(new OnDateChangeListener() {
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
Date d = new GregorianCalendar(year, month, dayOfMonth).getTime();
Intent intent = new Intent(activity, Activity.class);
intent.putExtra("DATE", d.getTime());
fragment.getContext().startActivity(intent);
}
});
在这种情况下,我们将millis传递给活动。 在活动中,您可以提取日期
Date d = new Date(getIntent().getLongExtra("DATE"));