Android time picker - java

I have used the code on this Android developers page to create a time picker when a button is pressed. However, I'm not getting the right look for it. I'm targeting my app to API 18 and the minimum is 10, because I want to support 2.3 due to the high usage. The minimum required SDK doesn't seem to have effect on the problem (I set it to 16):
I'm debugging the application on my HTC One S with Android 4.1.2, API 16. I get this kind of time picker but I want it to look modern, like in the Android developers page linked earlier.
http://www.b2creativedesigns.com/Tutorials/TimePicker/tutorial_timepicker2.png
Why does it use this prehistoric looking time picker?
I create the dialog using the following snippet. I call it from a FragmentActivity.
DialogFragment newFragment = TimePickerFragment.newInstance(2);
newFragment.show(getSupportFragmentManager(), "endtime");
This is the code for TimePickerFragment.
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
private static int id;
public static TimePickerFragment newInstance(int _id) {
Bundle args = new Bundle();
args.putInt("id", _id);
id = _id;
TimePickerFragment f = new TimePickerFragment();
f.setArguments(args);
return f;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
id = getArguments().getInt("id");
int hour = start / 60; // start is a global variable, no problems in these
int minute = start % 60;
if(id == 2) {
hour = end / 60;
minute = end % 60;
}
return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
System.out.println(hourOfDay + ":" + minute);
setTime(id, hourOfDay, minute);
}
}

Use ContextThemeWrapper to explicitly provide your Holo-based theme for the Dialog, e.g.
return new TimePickerDialog(
new ContextThemeWrapper(getActivity(), R.style.YourAppStyleInheritingFromHolo),
this, hour, minute, DateFormat.is24HourFormat(getActivity()));

You need to use the Holo theme for the Holo widgets to work in your app. For example :
in your Manifest, under application :
android:theme="#style/AppTheme"
and in your res/values folder :
<style name="AppBaseTheme" parent="android:Theme.Light.NoTitleBar">
</style>
while using this in values-v11 and values-v14 :
<style name="AppBaseTheme" parent="android:Theme.Holo.Light.NoActionBar">
</style>
The system will switch between Theme.Light and Theme.Holo.Light depending on the Android version on the device.

You might want to take a look at this library. It is a backported TimePicker from Android 4.2 which works from android 2.1 upwards.
https://github.com/SimonVT/android-timepicker

Related

Is it possible to change TimePicker default texts?

I need to change default text values on timepicker in android (java) and can't figure out how to do that.
I've found .setTitle and .setmessage, but when clicking on keyborad icon in Timepicker dialog:
and shows another way to change time it has another title and default message as instructions that I would like to change Second timepicker dialog output
.
I'm calling a simple TimePickerDialog. Any suggestions? regards
You can check this out. This works for me good.
#Subscribe
public void setAlarm(OnAlarmClickEvent event) {
arrivalTime = event.arrivalTime;
alarmTime = event.arrivalTime;
int reminder = Integer.parseInt(sharedPreferences.getString(getString(R.string.pref_key_alarm_reminder), "5"));
alarmTime = alarmTime.minusMinutes(reminder);
TimePickerDialog timePickerDialog = new TimePickerDialog(
this,
this,
alarmTime.getHourOfDay(),
alarmTime.getMinuteOfHour(),
DateFormat.is24HourFormat(this)
);
timePickerDialog.setTitle(R.string.alarm_dialog_title);
timePickerDialog.setMessage(getString(R.string.alarm_dialog_message_fmt, DateUtils.formatTime(arrivalTime)));
timePickerDialog.show();
}

How to use transition animations in API 16?

I wrote the following code:
Glide.with(this).asBitmap().load(userImageURL).into(new CustomViewTarget<ImageView, Bitmap>(userAvatarImage) {
#Override
protected void onResourceCleared(#Nullable Drawable placeholder) {
progressBarUserAvatar.setVisibility(View.GONE);
userAvatarImage.setImageBitmap(null);
}
#Override
public void onLoadFailed(#Nullable Drawable errorDrawable) {
progressBarUserAvatar.setVisibility(View.GONE);
final Bitmap circleLetterTile = tileProvider.getCircularLetterTile(userFullName);
userAvatarImage.setImageBitmap(circleLetterTile);
}
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
progressBarUserAvatar.setVisibility(View.GONE);
final Bitmap circleAvatarBitmap = tileProvider.getCircularImage(resource);
userAvatarImage.setImageBitmap(circleAvatarBitmap);
userAvatarImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent showProfilePictureIntent = new Intent(UserProfileActivity.this, DisplayUserImageActivity.class);
showProfilePictureIntent.putExtra("userImageURL",userImageURL);
final String transitionName = ViewCompat.getTransitionName(userAvatarImage);
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(
UserProfileActivity.this, userAvatarImage, transitionName);
UserProfileActivity.this.startActivity(showProfilePictureIntent, options.toBundle());
UserProfileActivity.this.overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
});
}
});
It basically displays the user's image using Glide. It also set a onClick listener that opens the image in large mode with black background. Currently, UserProfileActivity is empty (just loads the layout). The problem is that I can't use getTransitionName because it's possible only for api 21. I'm have to use API 16 in my project so it's a problem. What would be the easiest way to achieve it? I looked into previous topics but they all between 2013-2015 so I thought maybe there is a way to do it.
This is not possible to do, using API >21. As you can refer to the official documentation here https://developer.android.com/reference/android/app/ActivityOptions#makeSceneTransitionAnimation(android.app.Activity,%20android.view.View,%20java.lang.String).
I'm not sure, why you don't have warning usage, but do for getTransitionName. Unfortunately it's not supported on early version. As another reference you can check https://www.programcreek.com/java-api-examples/?class=android.app.ActivityOptions&method=makeSceneTransitionAnimation about examples how to use transition animation.
Off topic
You can achieve animation you want by writing own tools with transition animation. It's not so easy, but it's pure view implementation, and you don't need new Android version. For the same reason, you can use Flutter (min version for which is Android 16) and make transition animation (hero animation) with few lines of codes. Because it's out of box implementation.

How to keep the countDownTimer counts after i swap the activity?

i need a countDownTimer keep running when i swap between activities.. i have more than one activity, i put the countDownTimer in the main activity but when i swap to another activity and back to the main activity it turns back to count again from the start, i believe because the method countDownTimer is onCreate method.
So, how should I go about doing this?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionTime();
}
public void updateTimer(int secondsLeft){
int minutes = (int) secondsLeft / 60;
int seconds = secondsLeft - minutes * 60;
String secondString = Integer.toString(seconds);
timerTextView.setText(Integer.toString(minutes) + ":" + secondString);
}
private void questionTime(){
new CountDownTimer(10000, 1000){
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
timerTextView.setText("0:00");
Log.i("finished", "timer Done");
}
}.start();
}
Update: That helped me to reach my purpose How to run CountDownTimer in a Service in Android?
Maybe this is a little far fetched, but the way that I think to solve this issue and not worrying for the Activities is using an IntentService.
Even if you store some sort of value in the Bundle of the onSaveInstance() hook method this can lead to some pretty messy results if you enable the "Don't keep activities" flag in the device's settings.
What I would do is create an IntentService that when It's triggered starts the countdown, then It broadcast the changes of that countdown through EventBus/Otto/BroadcastReceiver back to the UI.
Another way of doing it is having the countdown instance in your Application class, and check it from there.
I would go with the IntentService solution because having a countdown instance running in the Application class sounds a little off.
Let me know if you want any specifics on how to implement the IntentService but a little bit of Googling should show you how to do it.
As soon as the time starts, write the time (unix timestamp) to properties file. And when the user comes back to your main activity, read the properties file and compare it the time in the properties file with current timestamp and update the timer based on that.

When is the TimePicker.OnTimeChangedListener exactly fired?

I am creating an Android application, and I am trying to use a TimePicker inside of it. I am trying to understand when exactly the OnTimeChangedListener is fired. I have this code inside of my onCreate method:
TimePicker.OnTimeChangedListener timeChangedListener =
new TimePicker.OnTimeChangedListener(){
#Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// My code is here...
}
};
I tried putting a breakpoint inside that block, but the program seems to never reach it. Here's the code in the XML layout for time picker:
<TimePicker
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="20dp"
android:paddingBottom="20dp"
android:id="#+id/time_picker"></TimePicker>
Should it get fired as soon as the user changes something in the TimePicker? Or does it wait till he enters hour, minute and AM or PM. Thanks in advance.
You should use TimePickerDialog.OnTimeSetListener
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
// your logic
}
};
You should get it by looking at the interface
imePicker view, int hourOfDay, int minute
it has hourOfDay and minute and the View itself..

Android apk works different in different devices

I'm developing an Android app. I have been testing it with the AVD (Nexus 5 API 22) and my LG G2 (5.0.2). When I released my first beta version I used a Moto G (4.4.4) to test it, and it works completely different.
E.g., when clicking a button, in the Moto G an item is added twice to a ListView, whereas in the other two works fine. Also in the G2 the background is not displayed, and in the other two it can be seen perfectly.
Right now I have tested it in a Xperia U (4.0.4) and everything works fine.
The Android Studio is configured for the API 15 in compiledSdkVersion, minSdkVersion and targetSdkVersion.
What's happening? I don't understand anything. What can I do to fix it?
EDIT: I add code snippets where the app fails.
TimePickerFragment class
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Alarm pickedAlarm = new Alarm();
int pk;
pickedAlarm.setHour(hourOfDay);
pickedAlarm.setMinute(minute);
pickedAlarm.setActivity(getActivity());
pk = db.insertNewAlarm(hourOfDay, minute);
pickedAlarm.set_id(pk);
pickedAlarm.setAdapter(adapter);
pickedAlarm.setDb(db);
adapter.add(pickedAlarm);
adapter.notifyDataSetChanged();
pickedAlarm.startCountdown(false);
Toast.makeText(getActivity().getApplicationContext(), "Alarm set and countdown started.", Toast.LENGTH_SHORT).show();
}
It seems that in Moto G this function is called twice...
MainActivity, when there is the botton to show the timePicker:
public void addAlarmClick(View view) {
TimePickerFragment timePicker = new TimePickerFragment();
timePicker.show(getFragmentManager(), "timePicker");
}

Categories