Не удается создать DatePicker в Android

#java #android #android-datepicker

#java #Android #android-datepicker

Вопрос:

Я только что написал программу для Android, которая состоит из DatePicker, но она не работает.

Код Java :

 public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        CurDateTv2 = (TextView)findViewById(R.id.textView2);
        Picker = (DatePicker)findViewById(R.id.calendarView1);
        btnChangeDate = (Button)findViewById(R.id.button1);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);
            Picker.init(year, month,day, onChangedListener())
            }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;


    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long

        int id = item.getItemId();
        if (id == R.id.action_settings) 
            return true;

        return super.onOptionsItemSelected(item);
    }
   public void onDateChangedListener(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
       CurDateTv2.setText(new String Builder()
               .append(dayOfMonth).append("/").append(monthOfYear   1)
               .aapend("/").append(year).append(" "));

   }
}
  

И макет

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button 
        android:id="@ id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Date" />

        <TextView
            android:id="@ id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Current Date"
            android:textAppearance="?android:attr/textAppearanceLarge"
            />

            <TextView
                android:id="@ id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="08/08/2016"
                android:textAppearance="?android:attr/textAppearanceLarge" 
                />

<CalendarView
                android:id="@ id/calendarView1"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
 />

    </LinearLayout>
  

К сожалению, я не очень хорошо знаю Java, поэтому не могу определить, где ошибка.
Я действительно надеюсь, что вы сможете мне помочь.

Комментарии:

1. Если вы объявили эту переменную ‘Picker’, а вторая каждая инициализация ресурсов должна выполняться только после метода setContentView (), сначала вы инициализируете ресурс, а затем вызываете setContentView (), поэтому измените его

2. Объявите свой сборщик, т.е. Picker = (DatePicker)findViewById(R.id.calendarView1); и другие переменные ниже super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

Ответ №1:

Рассмотрите возможность использования класса DialogFragment в средствах выбора даты и времени, чтобы сделать его доступным для использования в приложении и упростить работу со средствами выбора..

Смотрите Это официальное руководство для разработчиков.android:

https://developer.android.com/guide/topics/ui/controls/pickers.html

Ответ №2:

             //Initialize the variables
            Calendar myCalendar = Calendar.getInstance();
            DatePickerDialog.OnDateSetListener date;
            DatePickerDialog d1;



                //To be written in oncreate method

        //define
        date = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {
                // TODO Auto-generated method stub
                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);

        //It is a function that sets the value to the edittext after selection
                updateLabel();
            }
        };


    //onClick listener to the button which open the calendar
    fromDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            d1= new DatePickerDialog(className.this, date, myCalendar
                    .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                    myCalendar.get(Calendar.DAY_OF_MONTH));
            d1.show();
        }
    });

    //finally the function 
    private void updateLabel() {
        String myFormat = "MM/dd/yy"; //In which you need put here
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

    //Display the selection
        fromDateEdit.setText(sdf.format(myCalendar.getTime()));
    }
  

Ответ №3:

Это не требуется для просмотра календаря. Это возможно для редактирования текста.

Обратитесь:

http://androidopentutorials.com/android-datepickerdialog-on-edittext-click-event/