Sure! Here is a detailed guide on implementing a time picker with scrolling functionality in Android, along with two example explanations:
Step 1: Add Dependencies
To begin, make sure you have the necessary dependencies in your project's build.gradle
file:
dependencies {
implementation 'com.wdullaer:materialdatetimepicker:4.3.0'
}
Step 2: Create Layout
Next, create a layout file (activity_main.xml
) that contains the necessary views for the time picker:
<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"
android:layout_width=\"match_parent\"
android:layout_height=\"match_parent\"
android:orientation=\"vertical\">
<Button
android:id=\"@+id/btn_pick_time\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\"
android:text=\"Pick Time\" />
<TextView
android:id=\"@+id/tv_selected_time\"
android:layout_width=\"wrap_content\"
android:layout_height=\"wrap_content\"
android:text=\"Selected Time: \" />
</LinearLayout>
Step 3: Implement Time Picker
In your activity or fragment, implement the time picker functionality:
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import com.wdullaer.materialdatetimepicker.time.Timepoint;
public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
private TextView tvSelectedTime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvSelectedTime = findViewById(R.id.tv_selected_time);
Button btnPickTime = findViewById(R.id.btn_pick_time);
btnPickTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTimePicker();
}
});
}
private void showTimePicker() {
Calendar now = Calendar.getInstance();
TimePickerDialog timePickerDialog = TimePickerDialog.newInstance(
MainActivity.this,
now.get(Calendar.HOUR_OF_DAY),
now.get(Calendar.MINUTE),
true
);
timePickerDialog.show(getSupportFragmentManager(), \"TimePickerDialog\");
}
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
String selectedTime = String.format(Locale.getDefault(), \"%02d:%02d:%02d\", hourOfDay, minute, second);
tvSelectedTime.setText(\"Selected Time: \" + selectedTime);
}
}
In this example, we use the com.wdullaer:materialdatetimepicker
library to create the time picker. The showTimePicker()
method is called when the \"Pick Time\" button is clicked, which displays the time picker dialog. The selected time is then displayed in the TextView
.
That's it! You now have a time picker with scrolling functionality in your Android app. Feel free to customize the layout and appearance of the time picker according to your needs.
I hope this guide helps! Let me know if you have any further questions.
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Android 滚动时间选择的示例代码 - Python技术站