Android - 在TimePicker对话框中禁用(或隐藏)分钟选择

时间:2017-01-11 16:41:51

标签: android timepicker


在我的项目中,我使用 TimePicker对话框来允许用户选择时间。但我不希望他们选择分钟。所以,我想要的只是禁用(或隐藏)分钟选择。 那么,怎么做?

4 个答案:

答案 0 :(得分:1)

简短的回答是,你做不到。您必须创建自己的自定义对话框。

很长的答案是你可以,但你不应该。您可以找到视图的ID并禁用或隐藏它,但每个版本和制造商可能会对此对话框使用不同的ID,因此您将遇到许多问题和错误。

StackOverflow answer about hiding year

答案 1 :(得分:1)

没有库和简单的时间选择器

time_picker.setIs24HourView(true)
time_picker.currentMinute = 0
time_picker.currentHour = 0
time_picker.findViewById<View>(Resources.getSystem()
       .getIdentifier("hour", "id", "android"))
       .visibility = View.GONE

使用您需要隐藏或显示的内容更改ID标识符

答案 2 :(得分:0)

我使用Material TimePickerDialog Library解决了我的问题。

我的解决方案:

public class home extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, ... {
    ...
    private EditText time;
    private TimePickerDialog timePickerDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ...

        timePickerDialog = TimePickerDialog.newInstance(home.this, new Date().getHours(), new Date().getMinutes(), false);
        timePickerDialog.enableMinutes(false);

        time = (EditText) findViewById(R.id.time);
        time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                timePickerDialog.show(getFragmentManager(), "TimePickerDialog");
            }
        });
    }

    @Override
    public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
        String form;
        if (hourOfDay > 12) {
            hourOfDay = hourOfDay - 12;
            form = "PM";
        } else {
            if (hourOfDay == 0) {
                hourOfDay = 12;
            }
            form = "AM";
        }
        time.setText(String.valueOf(hourOfDay) + " " + form);
    }

    ...
}

答案 3 :(得分:0)

这解决了我的本地时间选择器组件问题
1.禁用分钟选择
2.隐藏时间分隔符
3.当用户选择小时

时,禁用从小时到分钟的过渡

代码在kotlin中。

// Disbale time picker minutes
time_picker.findViewById<View>(Resources.getSystem()
            .getIdentifier("minutes", "id", "android"))
            .visibility = View.GONE
// Disbale time seperator
time_picker.findViewById<View>(Resources.getSystem()
            .getIdentifier("separator", "id", "android"))
            .visibility = View.INVISIBLE

val delegateField = time_picker.javaClass.getDeclaredField("mDelegate")
delegateField.isAccessible = true;
val autoAdvance = delegateField.get(time_picker)
val autoAdvanceField = autoAdvance.javaClass.getDeclaredField("mAllowAutoAdvance")

autoAdvanceField.isAccessible = true
autoAdvanceField.set(autoAdvance, false)

输出:

enter image description here