학원/ANDROID

01/06 78-2[Android] clockpicker

도원결의 2023. 1. 7. 19:24


참고로

ScrollView 안에  태그를  많이 넣으면 에러남요

 

AnalogClock랑   DigitalClock은
걍 전시용 이걸로 값을가져올 수는 없다!

activity_main

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <AnalogClock
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"/>
        <DigitalClock
            android:layout_width="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:layout_height="match_parent"/>
    </LinearLayout>
    <!--ScrollView 안에 여러개 테그 넣으면 에러남 -->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            >
            <TimePicker
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:timePickerMode="spinner"
                />
            <DatePicker
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:datePickerMode="spinner"
                android:calendarViewShown="false"
                android:id="@+id/datePicker"
                />
        </LinearLayout>
    </ScrollView>

 

MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        DatePicker datePicker = findViewById(R.id.datePicker);
     /*방법1. 버전체크
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //API 레벨이26이상인 스마트 폰만 실행 됨
            datePicker.setOnDateChangedListener(new DatePicker.OnDateChangedListener() {
                @Override
                public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {

                }
            });
        }*/
        //방법2. 버전을 올린다. 그리들 모듈에서  minSdk 26로 변경 후 sync now 함!
        datePicker.setOnDateChangedListener(
                (Picker, year, month, dayOfMonth) ->
               //Toast.makeText(MainActivity.this, String.format("%s,%s,%s", year, month, dayOfMonth), Toast.LENGTH_SHORT).show()
            Log.i("com.kosmo.clockpicker",String.format("%s,%s,%s", year, month+1, dayOfMonth))
        );
    }

타이머 같은 기능 !

activity_main

※chronometer는 안드로이드에서 사용하는 아이디 고로
id로 설정하지 말아라

<Button
    android:id="@+id/btnTime"
    android:text="시간설정"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/btnDate"
    android:text="날짜설정"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
<Chronometer
    android:id="@+id/timer_chronometer"
    android:textSize="20sp"
    android:textStyle="italic|bold"
    android:textColor="#BD3636"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="안드로이드 OS부팅후 흘러온 시간"
    android:id="@+id/btnElaspedTime"
    />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:text="타이머"
        android:textSize="50sp" />

    <Button
        android:id="@+id/btnStop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textview"
        android:layout_alignRight="@id/textview"
        android:text="중지" />

    <Button
        android:id="@+id/btnStart"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textview"
        android:layout_toLeftOf="@id/btnStop"
        android:text="시작" />
</RelativeLayout>

그리들에

viewBinding {
            enabled = true
        }

바인딩 넣어놓고

 

MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Chronometer.OnChronometerTickListener { //현재 클래스가 이벤트 핸들러가 됨

    //테마를 @style/Theme.Material3.Dark.Dialog로 변경
    private ActivityMainBinding binding;

    private TimePickerDialog timePickerDialog;
    private DatePickerDialog datePickerDialog;

    private Calendar calendar = Calendar.getInstance();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //위젯에 리스너 부착
        binding.btnTime.setOnClickListener(this);
        binding.btnDate.setOnClickListener(this);
        binding.btnElaspedTime.setOnClickListener(this);
        binding.btnStart.setOnClickListener(this);
        binding.btnStop.setOnClickListener(this);
        binding.timerChronometer.setOnChronometerTickListener(this);

        //타임피커 타이얼로그 객체 생성
        /*
        context – the parent context
            themeResId – the resource ID of the theme to apply to this dialog
            listener – the listener to call when the time is set
            hourOfDay – the initial hour
            minute – the initial minute
            is24HourView – Whether this is a 24 hour view, or AM/PM.
        */

        timePickerDialog = new TimePickerDialog(
                this,
                android.R.style.Theme_Material_Dialog,
                (timePicker, hour, minute)->{
                    binding.textview.setText(String.format("%s시 %s분",hour,minute));
                },
                calendar.get(Calendar.HOUR),
                calendar.get(Calendar.MINUTE),
                true
        );
        /*
             context – the parent context
            listener – the listener to call when the user sets the date
            year – the initially selected year
            month – the initially selected month (0-11 for compatibility with Calendar.MONTH)
            dayOfMonth – the initially selected day of month (1-31, depending on month)
         */
        datePickerDialog = new DatePickerDialog(
                this,
                (datePicker,year,month,date) ->{
                    binding.textview.setText(String.format("%s년 %s월 %s일",year,month,date));
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH)+1,
                calendar.get(Calendar.DATE)

        );

    }////////////////////////onCreate

    //요 밑에서 이벤트 구현
    //버든의 클릭 이벤트 용
    @Override
    public void onClick(View view) {
        if(view.getId()== R.id.btnTime){
            if(!timePickerDialog.isShowing())  timePickerDialog.show();
        }
        else if(view.getId()==R.id.btnDate){
            if(!datePickerDialog.isShowing())  datePickerDialog.show();
        }
        else if(view.getId()==R.id.btnElaspedTime){
            SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
            Toast.makeText(this, dateFormat.format(new Date(SystemClock.elapsedRealtime())), Toast.LENGTH_SHORT).show();

        }
        else if(view.getId()==R.id.btnStart){
            //현재시간을 크로노미터의 기준 시간으로 설정
            binding.timerChronometer.setBase(SystemClock.elapsedRealtime());
            binding.timerChronometer.start();
        }
        else{
            binding.timerChronometer.stop();
        }
    }

    //크로노미터 틱 이벤트 용
    /*
    크로노미터는 디폴트로 분초로 표시됨
    아래코드 추가 시 시,분,초로 표시가능
    */

    //초가 변할때마다 자동으로 호출되는 콜백 메소드
    @Override
    public void onChronometerTick(Chronometer chronometer) {
        //크로미터를 시작한이후 플러온 시간
        long  elapsedTime =SystemClock.elapsedRealtime()-binding.timerChronometer.getBase();
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
        binding.timerChronometer.setText(dateFormat.format(new Date(elapsedTime)));
    }
}