android日历视图日期选择器

时间:2014-04-13 08:59:27

标签: android android-edittext android-datepicker

我想在用户按下DatePicker并选择日期后,为用户设置EditText以选择日期。我希望它返回到EditText字段。我怎么能这样做?

这是我的代码:

public class CompletedWorksActivity extends ActionBar {
    private TextView text_date;
    private DatePicker date_picker;
    private Button button;
    private EditText from;
    private EditText to;
    private int year;
    private int month;
    private int day;

    static final int DATE_DIALOG_ID = 100;



    @Override
    protected void onCreate(Bundle menuinstance){
        super.onCreate(menuinstance);
        setContentView(R.layout.completed_works);

        Intent intent = getIntent(); //gaunam
        User user = (User) intent.getSerializableExtra("user");
        from = (EditText) findViewById(R.id.datefrom);
        to = (EditText) findViewById(R.id.dateto);
    }


}

此代码需要xml:

<LinearLayout
    android:id="@+id/searchFields"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/header"
    android:background="#ffffff"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:paddingLeft="13dp"
    android:paddingRight="13dp"
    android:paddingTop="22dp" >

    <!-- Object ID field -->

    <EditText
        android:id="@+id/datefrom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="22dp"
        android:background="@drawable/search_datefrom_field"
        android:inputType="date"
        android:minHeight="45dp"
        android:paddingLeft="45dp"
        android:paddingRight="5dp"
        android:singleLine="true"
        android:textColor="#404041" />

    <!-- Key field -->

    <EditText
        android:id="@+id/dateto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="22dp"
        android:background="@drawable/search_dateto_field"
        android:inputType="date"
        android:minHeight="45dp"
        android:paddingLeft="45dp"
        android:paddingRight="5dp"
        android:singleLine="true"
        android:textColor="#404041" />
</LinearLayout>

以某种方式开始其他活动以选择带有选择器的日期或在此活动中拨打日期选择器是否更好?

4 个答案:

答案 0 :(得分:2)

我想我误解了你的描述,但无论如何我都会发布这个。

我的描述意味着您希望在点击DatePickerDialogfrom to时打开EditText。当获得焦点时,以下代码将打开对话框,然后将相应的EditText的文本设置为关闭时的日期。

public class CompletedWorksActivity extends Activity
implements DatePickerDialog.OnDateSetListener
{ 
    private TextView text_date;
    private Button button; 
    private EditText from; 
    private EditText to;
    private int year;
    private int month;
    private int day;

    private DatePickerDialog date_picker;
    private boolean fromEdit;

    @Override
    protected void onCreate(Bundle menuinstance)
    {
        super.onCreate(menuinstance);
        setContentView(R.layout.main);

        Intent intent = getIntent(); //gaunam
        User user = (User) intent.getSerializableExtra("user");

        from = (EditText) findViewById(R.id.datefrom);
        to = (EditText) findViewById(R.id.dateto);
        Calendar cal = Calendar.getInstance();

        date_picker = new DatePickerDialog(this, this, cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));        

        from.setOnFocusChangeListener(focusListener);

        to.setOnFocusChangeListener(focusListener);
    }

    @Override
    public void onDateSet(DatePicker dp, int y, int m, int d)
    {
        String cheapDate = (m + 1) + "/" + d + "/" + y;

        if (fromEdit)
        {
            from.setText(cheapDate);
        }
        else
        {
            to.setText(cheapDate);
        }
    }

    private View.OnFocusChangeListener focusListener = new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View v, boolean hasFocus)
        {           
            if (hasFocus)
            {
                //   \/ Optional \/
                EditText edit = (EditText) v;
                int len = edit.getText().toString().length();

                if (len == 0)
                {
                //   /\ Optional /\

                    fromEdit = v.getId() == R.id.datefrom;
                    date_picker.show();

                //   \/ Optional \/                 
                }
                else
                {
                    edit.setSelection(0, len);
                }
                //   /\ Optional /\
            }
        }
    };
}

修改

我清理了一些代码,并添加了其他功能,如果您愿意使用它。现在,当EditText获得焦点时,如果它是空的,它将打开对话框。如果它不为空,则对话框将显示,而是选择EditText的文本。

如果您只想打开,清空或不清空对话框,只需省略标记为“可选”评论之间的代码。

此外,从API Level 11(HONEYCOMB)开始,您可以执行以下操作:

date_picker.getDatePicker().setCalendarViewShown(true);

答案 1 :(得分:1)

仅在此活动中拨打日期选择器,这就是我喜欢的方式。这是像这样的事情

  private void callDatePic() {
    new DatePickerDialog(AddFriendActivity.this, d, c.get(Calendar.YEAR),
            c.get(Calendar.MONTH),       c.get(Calendar.DAY_OF_MONTH)).show();
}
DatePickerDialog.OnDateSetListener d = new OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
            int dayOfMonth) {
        date =  dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;          
        c1.set(Calendar.MONTH, monthOfYear);
        c1.set(Calendar.YEAR, year);
        c1.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                    dateFrom.setText(date);
    }

};
where c1 is Calender class object.

在此之后,您将返回编辑文本,其中edittext填充了所选日期。 您也可以按照其他编辑文本字段的相同步骤操作 希望这有帮助

答案 2 :(得分:1)

尝试使用此组件: https://github.com/truefedex/android-date-picker

像这样:

if (calendarPopup == null) {
  calendarPopup = new PopupWindow(getContext());
  CalendarPickerView calendarView = new CalendarPickerView(getContext());
  CalendarNumbersView calendar = (CalendarNumbersView) calendarView.findViewById(com.phlox.datepick.R.id.calendar);
  calendar.setShowDayNames(false);
  calendarView.setListener(onDateSelectionListener);
  calendarPopup.setContentView(calendarView);
  calendarPopup.setWindowLayoutMode(
        MeasureSpec.makeMeasureSpec(llCalendar.getWidth(), MeasureSpec.EXACTLY),
        ViewGroup.LayoutParams.WRAP_CONTENT);
  calendarPopup.setHeight(1);
  calendarPopup.setWidth(llCalendar.getWidth());
  calendarPopup.setOutsideTouchable(true);
}
calendarPopup.showAsDropDown(llCalendar);

答案 3 :(得分:0)

import java.util.Calendar;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethod;
import android.view.inputmethod.InputMethodManager;
import android.widget.DatePicker;
import android.widget.EditText;

 public class MainActivity extends Activity implements OnClickListener{
 EditText from,to;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);  
      //  User user = (User) intent.getSerializableExtra("user");
        from = (EditText) findViewById(R.id.datefrom);
        to = (EditText) findViewById(R.id.dateto);
        from.setOnClickListener(this);
        to.setOnClickListener(this);
}

@Override
public void onClick(final View v) {
    // To Hide KeyBoard 
    InputMethodManager i = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    i.hideSoftInputFromWindow(((EditText)v).getWindowToken(), 0);


    Calendar c = Calendar.getInstance();
    final String seperator = " / "; 
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day =  c.get(Calendar.DAY_OF_MONTH);
    OnDateSetListener listener = new OnDateSetListener() 
    {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                int dayOfMonth) {
            // YYYY/MM/DD
            //change the format as per your requirement
            ((EditText)v).setText(year + seperator + monthOfYear + seperator + dayOfMonth);

        }
    };

    DatePickerDialog d = new DatePickerDialog(this,listener,year , month, day);
    d.show();

}


 }

当用户点击任何编辑文本时,此代码将设置On Click Listener。 将打开DatePickerDialog框以选择日期