MainActivity.xml
<?xml version="1.0" encoding="utf-8"?>
<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="com.example.bhaumik.timepickers.MainActivity">
<TextView
android:id="@+id/tv_your_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Time"
android:textSize="24dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:textColor="@android:color/background_dark"/>
<Button
android:id="@+id/btn_select_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Select Time"
android:layout_marginTop="20dp"
android:textAllCaps="false"
/>
</LinearLayout>
MainActivity.java
package com.example.bhaumik.timepickers;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn_select_time);
textView = (TextView) findViewById(R.id.tv_your_time);
Calendar calendar = Calendar.getInstance();
final int hour = calendar.get(Calendar.HOUR_OF_DAY);
final int minute = calendar.get(Calendar.MINUTE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TimePickerDialog timePickerDialog = new TimePickerDialog(MainActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hours, int minuts) {
String str_hours;
if(hours<10){
str_hours = "0" + hours;
}
else
{
str_hours = "" + hours;
}
String str_minute;
if(minuts < 10){
str_minute = "0" + minuts;
}
else
{
str_minute = "" + minuts;
}
String status = "AM";
if(hours > 11){
status = "PM";
}
int hours_12;
if(hours > 11){
hours_12 = hours - 12;
}else
{
hours_12 = hours;
}
String time = hours_12 + " : " + str_minute + " : " + status;
textView.setText(time);
}
},hour,minute,false);
timePickerDialog.show();
}
});
}
}
0 comments:
Post a Comment