2017-08-29 29 views
-2

我在那里当你点击一个TextView它会打开一个对话框,从另一个布局的日期选择一个代码,我想要得到的日期,当我点击保存按钮,但它返回null。有我试过的代码:如何从一个datepicker日在对话框

fromDate.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      LayoutInflater factory = LayoutInflater.from(getActivity()); 
      final View textEntryView = factory.inflate(R.layout.calendar_view, null); 
      final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()); 
      alert.setTitle("Pick a date") 
        .setView(textEntryView) 
        .setPositiveButton("save", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, int whichButton) { 
            day = calendar.getDayOfMonth(); 
            month = calendar.getMonth(); 
            year = calendar.getYear(); 
            fromDate.setText(day+"/"+month+"/"+year); 
           } 
          }) 
        .setNegativeButton("Cancel", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog, 
                int whichButton) { 
           } 
          }); 
      alert.show(); 

fromDate是textview。

日,月,年是整数。

日历是日期选择器ID。

有谁知道为什么以及如何解决这个问题?

回答

0
fromDate.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
     Calendar mcurrentDate = Calendar.getInstance(); 
     final int mYear = mcurrentDate.get(Calendar.YEAR); 
     final int mMonth = mcurrentDate.get(Calendar.MONTH); 
     final int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH); 


    DatePickerDialog mDatePicker = new DatePickerDialog(SearchResultClass.this, R.style.MyDialogTheme, 
      new DatePickerDialog.OnDateSetListener() { 
       public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) { 

        fromDate.setText(selectedyear + "-" + month + "-" + selectedday); 

       } 
      }, mYear, mMonth, mDay); 
} 
    mDatePicker.setTitle(getString(R.string.datepicker_title2)); 
    mDatePicker.show(); 
}); 

并添加这个主题,你的styles.xml

<style name="MyDialogTheme"> 
    <item name="colorPrimary">@color/colorPrimary</item> 
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item> 
    <item name="colorAccent">@color/colorPrimary</item> 
</style> 
相关问题