7

如何在旋转视图中制作日期选择器。这是图像, 在此处输入图像描述

我希望日期选择器看起来像这样。提前致谢。

4

4 回答 4

9
@Override
parentView.findViewById(R.id.changeDate).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
         DialogFragment newFragment = new SelectDateFragmentTrans();
         newFragment.show(getFragmentManager(), "DatePicker");       
    }
});

SelectDateFragmentTrans.java:

public class SelectDateFragmentTrans extends DialogFragment
        implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar calendar = Calendar.getInstance();
        int yy = calendar.get(Calendar.YEAR);
        int mm = calendar.get(Calendar.MONTH);
        int dd = calendar.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), this, yy, mm, dd);
    }

    public void onDateSet(DatePicker view, int yy, int mm, int dd) {
        populateSetDate(yy, mm+1, dd);
    }

    public void populateSetDate(int year, int month, int day) {
        SettingsFragment.date1 = month+"/"+day+"/"+year;
        TransferFragment.date.setText(month+"/"+day+"/"+year);
    }
}
于 2015-07-09T12:05:27.107 回答
4

我想这会对你有所帮助

https://github.com/bendemboski/DateSlider

这是一个具有不同日期选择器类型和格式的自定义日期选择器。也很容易集成到您的应用程序中

于 2014-01-10T18:23:15.840 回答
3

我创建了一个自定义DatePicker,我想Months字符串中显示Jan,Feb,Mar,第二年是可选的。

所以我必须从scratch.

month_year_picker.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal">

        <NumberPicker
            android:id="@+id/picker_month"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="20dp"
            android:layout_marginRight="20dp"/>


        <NumberPicker
            android:id="@+id/picker_day"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="20dp"
            android:layout_marginRight="20dp"/>

        <NumberPicker
            android:id="@+id/picker_year"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

    </LinearLayout>
</LinearLayout>

MonthYearPickerDialog.java

public class MonthYearPickerDialog extends DialogFragment {

    private DatePickerDialog.OnDateSetListener listener;
    private int daysOfMonth = 31;

    private NumberPicker monthPicker;
    private NumberPicker yearPicker;
    private NumberPicker dayPicker;

    private Calendar cal = Calendar.getInstance();

    public static final String MONTH_KEY = "monthValue";
    public static final String DAY_KEY = "dayValue";
    public static final String YEAR_KEY = "yearValue";

    int monthVal = -1 , dayVal = -1 , yearVal =-1 ;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle extras = getArguments();
        if(extras != null){
            monthVal = extras.getInt(MONTH_KEY , -1);
            dayVal = extras.getInt(DAY_KEY , -1);
            yearVal = extras.getInt(YEAR_KEY , -1);
        }
    }

    public static MonthYearPickerDialog newInstance(int monthIndex , int daysIndex , int yearIndex) {
        MonthYearPickerDialog f = new MonthYearPickerDialog();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt(MONTH_KEY, monthIndex);
        args.putInt(DAY_KEY, daysIndex);
        args.putInt(YEAR_KEY, yearIndex);
        f.setArguments(args);

        return f;
    }

    public void setListener(DatePickerDialog.OnDateSetListener listener) {
        this.listener = listener;
    }


    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        //getDialog().setTitle("Select your Birthday Date");

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Get the layout inflater
        LayoutInflater inflater = getActivity().getLayoutInflater();

        View dialog = inflater.inflate(R.layout.month_year_picker, null);
        monthPicker = (NumberPicker) dialog.findViewById(R.id.picker_month);
        yearPicker = (NumberPicker) dialog.findViewById(R.id.picker_year);
        dayPicker = (NumberPicker) dialog.findViewById(R.id.picker_day);

        monthPicker.setMinValue(1);
        monthPicker.setMaxValue(12);


        if(monthVal != -1)// && (monthVal > 0 && monthVal < 13))
            monthPicker.setValue(monthVal);
        else
            monthPicker.setValue(cal.get(Calendar.MONTH) + 1);

        monthPicker.setDisplayedValues(new String[]{"Jan","Feb","Mar","Apr","May","June","July",
                "Aug","Sep","Oct","Nov","Dec"});


        dayPicker.setMinValue(1);
        dayPicker.setMaxValue(daysOfMonth);

        if(dayVal != -1)
            dayPicker.setValue(dayVal);
        else
            dayPicker.setValue(cal.get(Calendar.DAY_OF_MONTH));

        monthPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                switch (newVal){
                    case 1:case 3:case 5:
                    case 7:case 8:case 10:
                    case 12:
                        daysOfMonth = 31;
                        dayPicker.setMaxValue(daysOfMonth);
                        break;
                    case 2:
                        daysOfMonth = 28;
                        dayPicker.setMaxValue(daysOfMonth);
                        break;

                    case 4:case 6:
                    case 9:case 11:
                        daysOfMonth = 30;
                        dayPicker.setMaxValue(daysOfMonth);
                        break;
                }

            }
        });

        int maxYear = cal.get(Calendar.YEAR);//2016
        final int minYear = 1997;
        int arraySize = maxYear - minYear;

        String[] tempArray = new String[arraySize];
        tempArray[0] = "---";
        int tempYear = minYear+1;

        for(int i=0 ; i < arraySize; i++){
            if(i != 0){
                tempArray[i] = " " + tempYear + "";
            }
            tempYear++;
        }
        Log.i("", "onCreateDialog: " + tempArray.length);
        yearPicker.setMinValue(minYear+1);
        yearPicker.setMaxValue(maxYear);
        yearPicker.setDisplayedValues(tempArray);

        yearPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                try {
                    if(isLeapYear(picker.getValue())){
                        daysOfMonth = 29;
                        dayPicker.setMaxValue(daysOfMonth);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });

        builder.setView(dialog)
                // Add action buttons
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        int year = yearPicker.getValue();
                        if(year == (minYear+1)){
                            year = 1904;
                        }
                        listener.onDateSet(null, year, monthPicker.getValue(), dayPicker.getValue());
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MonthYearPickerDialog.this.getDialog().cancel();
                    }
                });
        return builder.create();
    }

    public static boolean isLeapYear(int year) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        return cal.getActualMaximum(Calendar.DAY_OF_YEAR) > 365;
    }

    public static boolean isLeapYear2(int year) {
        if (year % 4 != 0) {
            return false;
        } else if (year % 400 == 0) {
            return true;
        } else if (year % 100 == 0) {
            return false;
        } else {
            return true;
        }
    }
}

并称它为

MonthYearPickerDialog pd = MonthYearPickerDialog.newInstance(5,12, 1999);
                //new MonthYearPickerDialog();

        pd.setListener(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
                Toast.makeText(getActivity(),"Year : " + selectedYear + " Month :" + selectedMonth + " Day:" + selectedDay,
                        Toast.LENGTH_LONG ).show();


            }
        });
        pd.show(getFragmentManager(), "MonthYearPickerDialog");

编辑

在这里找到一个很好的例子

于 2016-06-17T11:11:34.310 回答
0

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.datepickerwithspinner.MainActivity">
<TextView
    android:id="@+id/tvdate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!" />
<Button
    android:id="@+id/Save"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tvdate"
    android:text="Date Picker"/>
  </RelativeLayout>

日期选择器对话框.java

import java.util.Calendar;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Typeface;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout.LayoutParams; 
import android.widget.TextView;
import com.wheel.ArrayWheelAdapter;
import com.wheel.NumericWheelAdapter;
import com.wheel.OnWheelChangedListener; 
import com.wheel.WheelView;

public class DatePickerDailog extends Dialog {

private Context Mcontex;

private int NoOfYear = 100;

public DatePickerDailog(Context context, Calendar calendar,
        final DatePickerListner dtp) {

    super(context);
    Mcontex = context;
    LinearLayout lytmain = new LinearLayout(Mcontex);
    lytmain.setOrientation(LinearLayout.VERTICAL);
    LinearLayout lytdate = new LinearLayout(Mcontex);
    LinearLayout lytbutton = new LinearLayout(Mcontex);

    Button btnset = new Button(Mcontex);
    Button btncancel = new Button(Mcontex);

    btnset.setText("Set");
    btncancel.setText("Cancel");

    final WheelView month = new WheelView(Mcontex);
    final WheelView year = new WheelView(Mcontex);
    final WheelView day = new WheelView(Mcontex);

    lytdate.addView(day, new LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1.2f));
    lytdate.addView(month, new LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 0.8f));
    lytdate.addView(year, new LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    lytbutton.addView(btnset, new LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1f));

    lytbutton.addView(btncancel, new LayoutParams(
            ViewGroup.LayoutParams.FILL_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
    lytbutton.setPadding(5, 5, 5, 5);
    lytmain.addView(lytdate);
    lytmain.addView(lytbutton);

    setContentView(lytmain);

    getWindow().setLayout(LayoutParams.FILL_PARENT,
            LayoutParams.WRAP_CONTENT);
    OnWheelChangedListener listener = new OnWheelChangedListener() {
        public void onChanged(WheelView wheel, int oldValue, int newValue) {
            updateDays(year, month, day);

        }
    };

    // month
    int curMonth = calendar.get(Calendar.MONTH);
    String months[] = new String[] { "January", "February", "March",
            "April", "May", "June", "July", "August", "September",
            "October", "November", "December" };
    month.setViewAdapter(new DateArrayAdapter(context, months, curMonth));
    month.setCurrentItem(curMonth);
    month.addChangingListener(listener);

    Calendar cal = Calendar.getInstance();
    // year
    int curYear = calendar.get(Calendar.YEAR);
    int Year = cal.get(Calendar.YEAR);


    year.setViewAdapter(new DateNumericAdapter(context, Year - NoOfYear,
            Year + NoOfYear, NoOfYear));
    year.setCurrentItem(curYear-(Year-NoOfYear));
    year.addChangingListener(listener);

    // day
    updateDays(year, month, day);
    day.setCurrentItem(calendar.get(Calendar.DAY_OF_MONTH) - 1);

    btnset.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Calendar c = updateDays(year, month, day);
            dtp.OnDoneButton(DatePickerDailog.this, c);
        }
    });
    btncancel.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            dtp.OnCancelButton(DatePickerDailog.this);

        }
    });

}

Calendar updateDays(WheelView year, WheelView month, WheelView day) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR,
            calendar.get(Calendar.YEAR) + (year.getCurrentItem()-NoOfYear));
    calendar.set(Calendar.MONTH, month.getCurrentItem());

    int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    day.setViewAdapter(new DateNumericAdapter(Mcontex, 1, maxDays, calendar
            .get(Calendar.DAY_OF_MONTH) - 1));
    int curDay = Math.min(maxDays, day.getCurrentItem() + 1);
    day.setCurrentItem(curDay - 1, true);
    calendar.set(Calendar.DAY_OF_MONTH, curDay);
    return calendar;

}

private class DateNumericAdapter extends NumericWheelAdapter {
    int currentItem;
    int currentValue;

    public DateNumericAdapter(Context context, int minValue, int maxValue,
            int current) {
        super(context, minValue, maxValue);
        this.currentValue = current;
        setTextSize(20);
    }

    @Override
    protected void configureTextView(TextView view) {
        super.configureTextView(view);
        if (currentItem == currentValue) {
            view.setTextColor(0xFF0000F0);
        }
        view.setTypeface(null, Typeface.BOLD);
    }

    @Override
    public View getItem(int index, View cachedView, ViewGroup parent) {
        currentItem = index;
        return super.getItem(index, cachedView, parent);
    }
}

private class DateArrayAdapter extends ArrayWheelAdapter<String> {
    int currentItem;
    int currentValue;

    public DateArrayAdapter(Context context, String[] items, int current) {
        super(context, items);
        this.currentValue = current;
        setTextSize(20);
    }

    @Override
    protected void configureTextView(TextView view) {
        super.configureTextView(view);
        if (currentItem == currentValue) {
            view.setTextColor(0xFF0000F0);
        }
        view.setTypeface(null, Typeface.BOLD);
    }

    @Override
    public View getItem(int index, View cachedView, ViewGroup parent) {
        currentItem = index;
        return super.getItem(index, cachedView, parent);
    }
}

public interface DatePickerListner {
    public void OnDoneButton(Dialog datedialog, Calendar c);

    public void OnCancelButton(Dialog datedialog);
}

}

MainActivity.java

import android.app.Dialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle; 
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

TextView tvDate;
Button btShow;

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

    tvDate=(TextView)findViewById(R.id.tvdate);
    btShow=(Button)findViewById(R.id.Save);
    dateandtime = Calendar.getInstance(Locale.US);

    btShow.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatePickerDailog dp = new DatePickerDailog(MainActivity.this,
                    dateandtime, new DatePickerDailog.DatePickerListner() {

                @Override
                public void OnDoneButton(Dialog datedialog, Calendar c) {
                    datedialog.dismiss();
                    dateandtime.set(Calendar.YEAR, c.get(Calendar.YEAR));
                    dateandtime.set(Calendar.MONTH,
                            c.get(Calendar.MONTH));
                    dateandtime.set(Calendar.DAY_OF_MONTH,
                            c.get(Calendar.DAY_OF_MONTH));
                    tvDate.setText(new SimpleDateFormat("dd MMMM yyyy")
                            .format(c.getTime()));
                }

                @Override
                public void OnCancelButton(Dialog datedialog) {
                    // TODO Auto-generated method stub
                    datedialog.dismiss();
                }
            });
            dp.show();


        }
    });

}
}

在 com 目录中添加名为 wheel 的文件夹,即 c:\DatePicker\app\src\main\java\com\wheel\

在 wheel 文件夹中 NumericWheelAdapter.java 即 c:\DatePicker\app\src\main\java\com\wheel\NumericWheelAdapter.java

import android.content.Context;

public class NumericWheelAdapter extends AbstractWheelTextAdapter {

/** The default min value */
public static final int DEFAULT_MAX_VALUE = 9;

/** The default max value */
private static final int DEFAULT_MIN_VALUE = 0;

// Values
private int minValue;
private int maxValue;

// format
private String format;


public NumericWheelAdapter(Context context) {
    this(context, DEFAULT_MIN_VALUE, DEFAULT_MAX_VALUE);
}


public NumericWheelAdapter(Context context, int minValue, int maxValue) {
    this(context, minValue, maxValue, null);
}


public NumericWheelAdapter(Context context, int minValue, int maxValue, String format) {
    super(context);

    this.minValue = minValue;
    this.maxValue = maxValue;
    this.format = format;
}

@Override
public CharSequence getItemText(int index) {
    if (index >= 0 && index < getItemsCount()) {
        int value = minValue + index;
        return format != null ? String.format(format, value) : Integer.toString(value);
    }
    return null;
}

@Override
public int getItemsCount() {
    return maxValue - minValue + 1;
}    
}

在wheel文件夹中创建两个接口 1. OnWheelClickedListener.java 2. OnWheelChangedListener.java

OnWheelClickedListener.java

 package com.wheel;

public interface OnWheelClickedListener {
void onItemClicked(WheelView wheel, int itemIndex);
}

OnWheelChangedListener.java

 package com.wheel;

 public interface OnWheelChangedListener {
 void onChanged(WheelView wheel, int oldValue, int newValue);
 }

像DatePicker这样的输出屏幕

日期选择器

于 2016-10-06T07:44:18.827 回答