Android日期选择器无法正常工作

q35jwt9p  于 2023-03-21  发布在  Android
关注(0)|答案(5)|浏览(123)

我正在尝试在android中实现一个日期选择器。日期选择器应该在点击按钮后出现。是的,我知道这很简单,但是作为一个初学者,我有点卡住了。下面是与任务相关的代码部分。

public class NeedFragment extends Fragment {

        private DatePicker datePicker;
        private Calendar calendar;
        private TextView dateView;
        private int year, month, day;
        Fragment fragment;
        String selectedDate=null;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

            View rootView = inflater.inflate(R.layout.fragment_need_blood, container, false);
            Button button1 = (Button)rootView.findViewById(R.id.dialog_btn1);

    button1.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    getActivity().showDialog(999);
                     if(selectedDate != null) {
                      Log.d("date",selectedDate); 
                     }
                    //openAppointments(dialog);
                }
            });
return rootView;
    }
    protected Dialog onCreateDialog(int id) {
              // TODO Auto-generated method stub
              if (id == 999) {
                 return new DatePickerDialog(getActivity().getApplicationContext()
                         , myDateListener, year, month, day);
              }
              return null;
           }

           private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
              @Override
              public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
                 // TODO Auto-generated method stub
                 // arg1 = year
                 // arg2 = month
                 // arg3 = day

                 StringBuilder sb=null;

                 sb.append(arg3).append("/")
                      .append(arg2+1).append("/").append(arg1);
                 returnDate(sb.toString());

              }
           };

           public void returnDate(String s)
           {
               selectedDate=s;
           }
       }

这是错误:

06-25 15:19:53.150: E/AndroidRuntime(13160): FATAL EXCEPTION: main
06-25 15:19:53.150: E/AndroidRuntime(13160): Process: com.bloodbank.slidingmenu, PID: 13160
06-25 15:19:53.150: E/AndroidRuntime(13160): java.lang.NullPointerException: println needs a message
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.util.Log.println_native_inner(Native Method)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.util.Log.println_native(Log.java:290)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.util.Log.d(Log.java:323)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at com.bloodbank.slidingmenu.NeedBloodFragment$3.onClick(NeedBloodFragment.java:220)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.view.View.performClick(View.java:4761)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.view.View$PerformClick.run(View.java:19767)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.os.Handler.handleCallback(Handler.java:739)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.os.Handler.dispatchMessage(Handler.java:95)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.os.Looper.loop(Looper.java:135)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at android.app.ActivityThread.main(ActivityThread.java:5312)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at java.lang.reflect.Method.invoke(Native Method)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at java.lang.reflect.Method.invoke(Method.java:372)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
06-25 15:19:53.150: E/AndroidRuntime(13160):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

编辑:以前的错误已解决。我还有一个问题。我可以开始一个活动后,我点击确定在日期对话框?

r1wp621o

r1wp621o1#

一旦更改以下行

getActivity().showDialog(999);

Dialog dialog=onCreateDialog(999);
 if(dialog!=null){
    dialog.show();
 }
1qczuiv0

1qczuiv02#

删除此行

Log.d("date",selectedDate);

并在返回日期内添加这一行

public void returnDate(String s) { 
     selectedDate=s; 
     Log.d("date",selectedDate); 
}
1l5u6lss

1l5u6lss3#

试试这个代码

public class NeedFragment extends Fragment {

private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
Fragment fragment;
String selectedDate="";

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_need_blood, container, false);
    Button button1 = (Button)  rootView.findViewById(R.id.dialog_btn1);
    button1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            onCreateDialog(999);
            Log.d("date",selectedDate);
            //openAppointments(dialog);
        }
    });
  return rootView;
  }
  public Dialog onCreateDialog(int id) {
      // TODO Auto-generated method stub
      if (id == 999) {
         return new DatePickerDialog(getActivity()
                 , myDateListener, year, month, day);
      }
      return null;
   }

   public DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
      @Override
      public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
         // TODO Auto-generated method stub
         // arg1 = year
         // arg2 = month
         // arg3 = day

         StringBuilder sb=null;

         sb.append(arg3).append("/")
              .append(arg2+1).append("/").append(arg1);
         returnDate(sb.toString());

      }
   };

   public void returnDate(String s)
   {
       selectedDate=s;
   }
 }
3lxsmp7m

3lxsmp7m4#

在主Activity中尝试这段代码,然后在布局中使用正确的id名称创建一个按钮和文本视图并运行它,您可以在http://www.ahotbrew.com/android-datepicker-example/上找到完整的博客文章及其源代码

package com.ahotbrew.datepicker;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends ActionBarActivity {

    public static TextView SelectedDateView;

    public static class DatePickerFragment extends DialogFragment
            implements DatePickerDialog.OnDateSetListener {

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            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);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            SelectedDateView.setText("Selected Date: " + (month + 1) + "-" + day + "-" + year);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SelectedDateView = (TextView) findViewById(R.id.selected_date);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void showDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }
}
mzillmmw

mzillmmw5#

public class MainActivity extends AppCompatActivity {

    DatePicker dtpicker;

    Button btntoday;

    TextView textView;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        textView=(TextView)findViewById(R.id.tv1);

        dtpicker=(DatePicker)findViewById(R.id.dtpcr);

        btntoday=(Button)findViewById(R.id.btn);

        btntoday.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                textView.setText("Selected Date: "+ dtpicker.getDayOfMonth()+"/"+ (dtpicker.getMonth() + 1)+"/"+dtpicker.getYear());

            }

        });

    }

}

步骤2.活动_主文件. xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:id="@+id/tv"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"


        android:layout_marginLeft="100dp"

        android:layout_marginTop="10dp"

        android:textStyle="bold"

        android:text="DatePicker Example"

        android:textSize="18dp"/>


    <DatePicker

        android:id="@+id/dtpcr"

        android:layout_below="@+id/tv"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="25dp" />

    <Button

        android:id="@+id/btn"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/dtpcr"

        android:layout_marginLeft="100dp"

        android:text="Selected Date" />

    <TextView

        android:id="@+id/tv1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@+id/btn"

        android:layout_marginLeft="100dp"

        android:layout_marginTop="10dp"

        android:textStyle="bold"

        android:textSize="18dp"/>
</RelativeLayout>

访问此https://solutioninpocket.com/posts/android-datepicker-example

相关问题