Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative way to access TimePickerDialog's NumberPicker objects than Class.forName

I am trying to create a custom TimePickerDialog with custom intervals for hours and minutes, and managed to solve it by using the answer from this question.

The problem is that Android Studio displays the following warning:

Accessing internal APIs via reflection is not supported and may not work on all devices, or in the future. Using reflection to access hidden/private Android APIs is not safe; it will often not work on devices from other vendors, and it may suddenly stop working[...]

The issue is in line one:

Class<?> classForid = Class.forName("com.android.internal.R$id");

Field timePickerField = classForid.getField("timePicker");
TimePicker mTimePicker = findViewById(timePickerField.getInt(null));
Field minuteField = classForid.getField("minute");
Field hourField = classForid.getField("hour");
NumberPicker minutePicker = mTimePicker.findViewById(minuteField.getInt(null));
NumberPicker hourPicker = mTimePicker.findViewById(hourField.getInt(null));

I need some alternative way of accessing the two NumberPicker objects.

like image 982
Developer Avatar asked Dec 18 '22 15:12

Developer


1 Answers

I found a solution by using Resources.getSystem().getIdentifier().

The code now looks like this:

TimePicker timePicker = findViewById(Resources.getSystem().getIdentifier(
    "timePicker", 
    "id", 
    "android"
));

NumberPicker minutePicker = timePicker.findViewById(Resources.getSystem().getIdentifier(
    "minute", 
    "id", 
    "android"
));

NumberPicker hourPicker = timePicker.findViewById(Resources.getSystem().getIdentifier(
    "hour", 
    "id", 
    "android"
));
like image 105
Developer Avatar answered Dec 20 '22 06:12

Developer