2016-11-04 95 views
2

如何設置timepicker中的最短時間(我沒有使用TimePickerDialog)。我搜查了很多,但無法找到正確的答案。我使用TimePicker從用戶處獲得時間。這是我的XML代碼如何在Android TimePicker中設置最短時間(不在TimePickerDialog中)

   <TimePicker 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:layout_centerVertical="true" 
        android:layout_alignParentLeft="true" 
        android:layout_alignParentStart="true" 
        android:headerBackground="@color/colorPrimary" 
        android:id="@+id/timePicker" /> 

這是我在我的代碼

TimePicker timePicker = (TimePicker) findViewById(R.id.timePicker); 

怎麼弄現在我該怎麼設置最短時間綁定用戶不要選擇過去的時間。

這就是我的時間選擇器的樣子....我沒有使用TimePickerDialog,因爲我們必須隨時間顯示不同的東西。謝謝!

enter image description here

回答

1

創建一個XML文件,並將其命名爲activity_time_picker.xml

​​

現在創建活動課這樣

import java.lang.reflect.Field; 
import java.util.ArrayList; 
import java.util.List; 

import android.annotation.SuppressLint; 

import android.content.pm.ActivityInfo; 
import android.os.Bundle; 
import android.view.View; 
import android.view.Window; 
import android.widget.NumberPicker; 
import android.widget.TimePicker; 

public class TimePickerActivity extends Activity { 


    TimePicker timePicker; 
    private int TIME_PICKER_INTERVAL = 15; 
    NumberPicker minutePicker; 
    List<String> displayedValues; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
       super.onCreate(savedInstanceState); 
     setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 
     setContentView(R.layout.activity_time_picker); 
     super.onCreate(savedInstanceState); 
     timePicker = (TimePicker)findViewById(R.id.timePicker1); 

     timePicker.setIs24HourView(true); 
     timePicker.setCurrentHour(0); 
     timePicker.setCurrentMinute(0); 

     setTimePickerInterval(timePicker); 
    } 
@SuppressLint("NewApi") 
    private void setTimePickerInterval(TimePicker timePicker) { 
     try { 
       Class<?> classForid = Class.forName("com.android.internal.R$id"); 
       // Field timePickerField = classForid.getField("timePicker"); 

       Field field = classForid.getField("minute"); 
       minutePicker = (NumberPicker) timePicker 
         .findViewById(field.getInt(null)); 

       minutePicker.setMinValue(0); 
       minutePicker.setMaxValue(3); 
       displayedValues = new ArrayList<String>(); 
       for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) { 
        displayedValues.add(String.format("%02d", i)); 
       } 
       // for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) { 
       //  displayedValues.add(String.format("%02d", i)); 
       // } 
       minutePicker.setDisplayedValues(displayedValues 
         .toArray(new String[0])); 
       minutePicker.setWrapSelectorWheel(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
    } 
} 
相關問題