当用户单击datePicker中的某个日期时,如何从当前活动转到上一个片段。我可以将该时间戳存储到我的数据库中吗,实际上我想将该日期保存在某个变量中并将其传输到我的数据库中。请帮我,我是Android新手
date_activity.java
public class DatePick extends AppCompatActivity {
DatePicker datep;
public long date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.date_layout);
datep = findViewById(R.id.datePicker);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
date=calendar.getTimeInMillis();
Intent intent = new Intent();
intent.putExtra("date", date);
setResult(Activity.RESULT_OK, intent);
finish();
}
Fragment.java
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
CardView cd= view.findViewById(R.id.card);
cd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
date_Frag();
}
});
}
public void date_Frag() {
Intent intent = new Intent(this.getActivity(), DatePick.class);
startActivityForResult(intent,11111);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 11111 && resultCode == Activity.RESULT_OK) {
long date = data.getExtras().getLong("date");
}
最佳答案
如果您只想关闭活动(而不需要发送回数据),则只需在finish()
活动中调用DatePick
。
如果要将数据从DatePick
活动发送回片段,可以使用onActivityResult()
。
例如,首先使用startActivityForResult
开始第二个活动:
Intent i = new Intent(this, DatePick.class);
startActivityForResult(i, 11111);
使用
DatePick
从setResult
发送回数据:Intent intent = new Intent();
intent.putExtra("date", date);
setResult(Activity.RESULT_OK, intent);
finish();
并读回到片段中:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 11111 && resultCode == Activity.RESULT_OK) {
long date = data.getExtras().getLong("date");
}
}
See this for detailed usage examples