top of page

Learn Android App Dev: Picking Time using Clock

Hey Guys! In this post, I'll be talking about how to pick from a clock which will be shown in our App. This is a simple App which does the job of the showing the Time in a Toast message. Time Picking is used when we have to choose time say for ex, you have to set a reminder for a specific time, then you can use Time Picker.

So here are the steps:

1. First of all, drag a TimePicker from the widgets and also drag a button for showing the Time in toast message. So your app will look like:

2. Now you need to write the Java code. Declare the timepicker and Button in your MainActivtity class.

3. Now create a function for showing the time. Cast your TimePicker and Button variable in this function.

4. Now create a new OnClickListener for the button. Use this syntax for showing the time. .

5. Now everything's done. You can run your App.

Here's the Java code:

package com.example.ameylokhande.time;

import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TimePicker; import android.widget.Toast;

public class MainActivity extends AppCompatActivity { private static TimePicker time; private static Button btn;

@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void show(){ time = (TimePicker)findViewById(R.id.timePicker2); btn = (Button)findViewById(R.id.button);

btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,time.getCurrentHour() + ":" + time.getCurrentMinute(),Toast.LENGTH_LONG) .show();

} }); } }

Thanks for reading! Stay tuned for further updates!

bottom of page