Android Studio 日期选择器和时间选择器

Android开发从入门到精通(案例版1)
·日期选择器
首先是.xml文件,主要就是加入标签








在看activity,


import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.Toast;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    int year,month,day;
    DatePicker datePicker;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        datePicker=findViewById(R.id.datePicker1);
        Calendar calendar=Calendar.getInstance();
        /**
         * 初始化时获得日期
         */
        year=calendar.get(Calendar.YEAR);
        month=calendar.get(Calendar.MONTH);
        day=calendar.get(Calendar.DAY_OF_MONTH);

        datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker datePicker, int year1, int month1, int day1) {
                /**
                *year1,month1,day1是改变后获取的新日期
                 */
                MainActivity.this.year=year1;
                MainActivity.this.month=month1;
                MainActivity.this.day=day1;
                show(year,month,day);
            }
        });
    }
    private void show(int i, int i1, int i2) {
        String  str=i+"年"+(1+i1)+"月"+i2+'日';
        //用Toast显示变化后的日期
        Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
    }
}

图片展示:
Android Studio 日期选择器和时间选择器_第1张图片·时间选择器

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TimePicker timePicker=findViewById(R.id.timePicker);
        //默认是12小时,setIs24HourView设置成24小时·
        timePicker.setIs24HourView(true);
        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minute) {
                String str=hourOfDay+"时"+minute+"分";
                Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
            }
        });
    }

}

你可能感兴趣的:(Android,Studio)