Example usage for android.widget NumberPicker setValue

List of usage examples for android.widget NumberPicker setValue

Introduction

In this page you can find the example usage for android.widget NumberPicker setValue.

Prototype

public void setValue(int value) 

Source Link

Document

Set the current value for the number picker.

Usage

From source file:obdii.starter.automotive.iot.ibm.com.iot4a_obdii.Home.java

public void changeFrequency(View view) {
    // called from UI panel
    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(Home.this,
            R.style.AppCompatAlertDialogStyle);
    final View changeFrequencyAlert = getLayoutInflater().inflate(R.layout.activity_home_changefrequency, null,
            false);//from   w  w w. j a  v a  2 s.c  om

    final NumberPicker numberPicker = (NumberPicker) changeFrequencyAlert.findViewById(R.id.numberPicker);
    final int frequency_sec = getUploadFrequencySec();
    numberPicker.setMinValue(MIN_FREQUENCY_SEC);
    numberPicker.setMaxValue(MAX_FREQUENCY_SEC);
    numberPicker.setValue(frequency_sec);

    alertDialog.setView(changeFrequencyAlert);
    alertDialog.setCancelable(false).setTitle("Change the Frequency of Data Being Sent (in Seconds)")
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int which) {
                    final int value = numberPicker.getValue();
                    if (value != frequency_sec) {
                        setUploadFrequencySec(value);
                        startObdScan();
                        startPublishingProbeData();
                    }
                }
            }).setNegativeButton("Cancel", null).show();
}

From source file:com.crcrch.chromatictuner.app.NotePickerFragment.java

@NonNull
@Override//www  .j a va  2  s .  co  m
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());

    View dialogContent = LayoutInflater.from(dialogBuilder.getContext()).inflate(R.layout.fragment_note_picker,
            null);

    final NumberPicker notePicker = (NumberPicker) dialogContent.findViewById(R.id.picker_note);
    notePicker.setMinValue(0);
    notePicker.setMaxValue(MiscMusic.CHROMATIC_SCALE.length - 1);
    notePicker.setDisplayedValues(MiscMusic.CHROMATIC_SCALE);
    notePicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

    final NumberPicker octavePicker = (NumberPicker) dialogContent.findViewById(R.id.picker_octave);
    octavePicker.setMinValue(0);
    octavePicker.setMaxValue(MAX_OCTAVE);
    octavePicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
    octavePicker.setWrapSelectorWheel(false);

    final TextView frequencyView = (TextView) dialogContent.findViewById(R.id.frequency);
    notePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            frequencyView.setText(selectFrequency(newVal, octavePicker.getValue()));
        }
    });
    octavePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            frequencyView.setText(selectFrequency(notePicker.getValue(), newVal));
        }
    });

    double frequencyToDisplay;
    if (savedInstanceState == null) {
        frequencyToDisplay = initialFrequency;
    } else {
        frequencyToDisplay = savedInstanceState.getDouble(STATE_FREQUENCY);
    }
    frequencyView.setText(selectFrequency(frequencyToDisplay));
    int note = getNoteForFrequency(frequencyToDisplay);
    octavePicker.setValue(getOctaveForNote(note));
    octavePicker.invalidate();
    notePicker.setValue(getNoteIndexForNote(note));
    notePicker.invalidate();

    return dialogBuilder.setTitle(R.string.dialog_title_note_picker).setView(dialogContent)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    listener.onFrequencySelected(frequency);
                    dialog.dismiss();
                }
            }).setNegativeButton(android.R.string.cancel, null).create();
}

From source file:com.almalence.plugins.capture.video.VideoCapturePlugin.java

public void TimeLapseDialog() {
    if (isRecording)
        return;/* w w  w .  jav  a 2 s  .  c  o  m*/

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ApplicationScreen.getMainContext());
    interval = Integer.valueOf(prefs.getString("timelapseInterval", "0"));
    measurementVal = Integer.valueOf(prefs.getString("timelapseMeasurementVal", "0"));

    // show time lapse settings
    timeLapseDialog = new TimeLapseDialog(ApplicationScreen.instance);
    timeLapseDialog.setContentView(R.layout.plugin_capture_video_timelapse_dialog);
    final NumberPicker np = (NumberPicker) timeLapseDialog.findViewById(R.id.numberPicker1);
    np.setMaxValue(16);
    np.setMinValue(0);
    np.setValue(interval);
    np.setDisplayedValues(stringInterval);
    np.setWrapSelectorWheel(false);
    np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

    final NumberPicker np2 = (NumberPicker) timeLapseDialog.findViewById(R.id.numberPicker2);
    np2.setMaxValue(2);
    np2.setMinValue(0);
    np2.setValue(measurementVal);
    np2.setWrapSelectorWheel(false);
    np2.setDisplayedValues(stringMeasurement);
    np2.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);

    final Switch sw = (Switch) timeLapseDialog.findViewById(R.id.timelapse_switcher);

    // disable/enable controls in dialog
    sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (!sw.isChecked()) {
                swChecked = false;
            } else {
                swChecked = true;
            }
        }
    });

    np2.setOnScrollListener(new NumberPicker.OnScrollListener() {
        @Override
        public void onScrollStateChange(NumberPicker numberPicker, int scrollState) {
            sw.setChecked(true);
        }
    });
    np.setOnScrollListener(new NumberPicker.OnScrollListener() {
        @Override
        public void onScrollStateChange(NumberPicker numberPicker, int scrollState) {
            sw.setChecked(true);
        }
    });

    // disable control in dialog by default
    if (!swChecked) {
        sw.setChecked(false);
    } else {
        sw.setChecked(true);
    }

    timeLapseDialog.setOnDismissListener(new OnDismissListener() {
        @Override
        public void onDismiss(DialogInterface dialog) {
            if (swChecked) {
                measurementVal = np2.getValue();
                interval = np.getValue();

                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(ApplicationScreen.getMainContext());
                Editor editor = prefs.edit();
                editor.putString("timelapseMeasurementVal", String.valueOf(measurementVal));
                editor.putString("timelapseInterval", String.valueOf(interval));
                editor.commit();

                timeLapseButton.setImageDrawable(ApplicationScreen.getAppResources()
                        .getDrawable(R.drawable.plugin_capture_video_timelapse_active));

                ApplicationScreen.getGUIManager().setShutterIcon(ShutterButton.RECORDER_START);
            } else {
                timeLapseButton.setImageDrawable(ApplicationScreen.getAppResources()
                        .getDrawable(R.drawable.plugin_capture_video_timelapse_inactive));
                ApplicationScreen.getGUIManager().setShutterIcon(ShutterButton.RECORDER_START);
            }

        }
    });
    timeLapseDialog.show();
}

From source file:com.bt.heliniumstudentapp.GradesFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
    mainContext = (AppCompatActivity) getActivity();
    gradesLayout = inflater.inflate(R.layout.fragment_grades, viewGroup, false);

    boolean pass = true;

    if (gradesHtml == null) {
        termFocus = Integer.parseInt(
                PreferenceManager.getDefaultSharedPreferences(mainContext).getString("pref_grades_term", "1"));
        yearFocus = 0;//  w  ww.j  a  va 2  s  .  co m

        if (Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(mainContext)
                .getString("pref_general_class", "0")) == 0) {
            try { //TODO Improve
                maxYear = Integer.parseInt(((TextView) mainContext.findViewById(R.id.tv_class_hd)).getText()
                        .toString().replaceAll("\\D+", ""));
            } catch (NumberFormatException e) {
                pass = false;

                MainActivity.drawerNV.getMenu().findItem(R.id.i_schedule_md).setChecked(true);
                MainActivity.FM.beginTransaction()
                        .replace(R.id.fl_container_am, new ScheduleFragment(), "SCHEDULE").commit();

                final AlertDialog.Builder classDialogBuilder = new AlertDialog.Builder(
                        new ContextThemeWrapper(mainContext, MainActivity.themeDialog));

                classDialogBuilder.setTitle(R.string.error);
                classDialogBuilder.setMessage(R.string.error_class);

                classDialogBuilder.setCancelable(false);

                classDialogBuilder.setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mainContext.startActivity(new Intent(mainContext, SettingsActivity.class));
                            }
                        });

                classDialogBuilder.setNegativeButton(android.R.string.cancel, null);

                final AlertDialog classDialog = classDialogBuilder.create();

                classDialog.setCanceledOnTouchOutside(false);
                classDialog.show();

                classDialog.getButton(AlertDialog.BUTTON_POSITIVE)
                        .setTextColor(ContextCompat.getColor(mainContext, MainActivity.accentSecondaryColor));
                classDialog.getButton(AlertDialog.BUTTON_NEGATIVE)
                        .setTextColor(ContextCompat.getColor(mainContext, MainActivity.accentSecondaryColor));
            }
        } else {
            maxYear = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(mainContext)
                    .getString("pref_general_class", "1"));
        }
    }

    if (pass) {
        MainActivity.setToolbarTitle(mainContext, getString(R.string.grades), null);

        gradesELV = (ExpandableListView) gradesLayout.findViewById(R.id.lv_course_fg);

        final boolean online = MainActivity.isOnline();

        if (PreferenceManager.getDefaultSharedPreferences(mainContext).getString("html_grades", null) == null) { //TODO Simpler
            if (online) {
                getGrades(termFocus, HeliniumStudentApp.df_date().format(new Date()),
                        HeliniumStudentApp.DIREC_CURRENT, HeliniumStudentApp.ACTION_INIT_IN);
            } else { //TODO Display empty GradesFragment with retry option
                Toast.makeText(mainContext, getString(R.string.database_no), Toast.LENGTH_SHORT).show();

                MainActivity.drawerNV.getMenu().findItem(R.id.i_schedule_md).setChecked(true);
                MainActivity.FM.beginTransaction()
                        .replace(R.id.fl_container_am, new ScheduleFragment(), "SCHEDULE").commit();
            }
        } else if (online && gradesHtml == null && PreferenceManager.getDefaultSharedPreferences(mainContext)
                .getBoolean("pref_grades_init", true)) {
            getGrades(termFocus, HeliniumStudentApp.df_date().format(new Date()),
                    HeliniumStudentApp.DIREC_CURRENT, HeliniumStudentApp.ACTION_INIT_IN);
        } else {
            if (gradesHtml == null)
                gradesHtml = PreferenceManager.getDefaultSharedPreferences(mainContext).getString("html_grades",
                        null);

            if (online)
                parseData(HeliniumStudentApp.ACTION_ONLINE);
            else
                parseData(HeliniumStudentApp.ACTION_OFFLINE);
        }

        ((SwipeRefreshLayout) gradesLayout).setColorSchemeResources(MainActivity.accentSecondaryColor,
                MainActivity.accentPrimaryColor, MainActivity.primaryColor);
        ((SwipeRefreshLayout) gradesLayout).setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                refresh();
            }
        });

        gradesELV.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            int previousPosition = -1;

            @Override
            public void onGroupExpand(int position) {
                if (position != previousPosition)
                    gradesELV.collapseGroup(previousPosition);
                previousPosition = position;
            }
        });

        gradesELV.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { //Just a little easter egg
            int clickCount = 1;

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int position,
                    long id) {
                if (clickCount >= 80) {
                    Toast.makeText(mainContext, "Is this what you wanted?", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://youtu.be/dQw4w9WgXcQ")));
                } else {
                    switch (clickCount) {
                    case 2:
                        Toast.makeText(mainContext, "Good for you!", Toast.LENGTH_SHORT).show();
                        break;
                    case 10:
                        Toast.makeText(mainContext, "You're really proud of that, aren't you?",
                                Toast.LENGTH_SHORT).show();
                        break;
                    case 20:
                        Toast.makeText(mainContext, "It's really not that big of a deal...", Toast.LENGTH_SHORT)
                                .show();
                        break;
                    case 40:
                        Toast.makeText(mainContext, "You can stop now.", Toast.LENGTH_SHORT).show();
                        break;
                    case 50:
                        Toast.makeText(mainContext, "Please...", Toast.LENGTH_SHORT).show();
                    case 60:
                        Toast.makeText(mainContext, "F* OFF!", Toast.LENGTH_SHORT).show();
                        break;
                    }
                }

                clickCount++;
                return false;
            }
        });

        MainActivity.prevIV.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (MainActivity.isOnline()) {
                    if (termFocus != 1) {
                        termFocus--;

                        getGrades(termFocus, HeliniumStudentApp.df_grades(yearFocus),
                                HeliniumStudentApp.DIREC_BACK, HeliniumStudentApp.ACTION_REFRESH_IN);
                    } else {
                        MainActivity.setUI(HeliniumStudentApp.VIEW_GRADES, HeliniumStudentApp.ACTION_ONLINE);
                    }
                } else {
                    final int databaseFocus = Integer.parseInt(PreferenceManager
                            .getDefaultSharedPreferences(mainContext).getString("pref_grades_term", "1"));

                    if (PreferenceManager.getDefaultSharedPreferences(mainContext).getString("html_grades",
                            null) != null && yearFocus == 0 && termFocus > databaseFocus) {
                        yearFocus = 0;
                        termFocus = databaseFocus;

                        gradesHtml = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("html_grades", null);
                        parseData(HeliniumStudentApp.ACTION_OFFLINE);
                    } else {
                        MainActivity.setUI(HeliniumStudentApp.VIEW_GRADES, HeliniumStudentApp.ACTION_OFFLINE);
                    }
                }
            }
        });

        MainActivity.historyIV.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (MainActivity.isOnline()) {
                    if (maxYear != 1) {
                        MainActivity.setUI(HeliniumStudentApp.VIEW_GRADES, HeliniumStudentApp.ACTION_ONLINE);

                        final AlertDialog.Builder gradesDialogBuilder = new AlertDialog.Builder(
                                new ContextThemeWrapper(mainContext, MainActivity.themeDialog));
                        final View gradesLayout = View.inflate(mainContext, R.layout.dialog_grades, null);

                        gradesDialogBuilder.setTitle(getString(R.string.year, maxYear));

                        final NumberPicker yearNP = (NumberPicker) gradesLayout.findViewById(R.id.np_year_dg);

                        gradesDialogBuilder.setView(gradesLayout);

                        //TODO Listen for year change.

                        gradesDialogBuilder.setPositiveButton(android.R.string.ok,
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (MainActivity.isOnline()) {
                                            final int oldValue = yearFocus;

                                            yearFocus = yearNP.getValue() - maxYear;
                                            getGrades(termFocus, HeliniumStudentApp.df_grades(yearFocus),
                                                    oldValue + HeliniumStudentApp.FOCUS_YEAR,
                                                    HeliniumStudentApp.ACTION_REFRESH_IN);
                                        } else {
                                            Toast.makeText(mainContext, getString(R.string.error_conn_no),
                                                    Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });

                        yearNP.setMinValue(1);
                        yearNP.setMaxValue(maxYear);

                        yearNP.setValue(maxYear);

                        java.lang.reflect.Field[] pickerFields = NumberPicker.class.getDeclaredFields();
                        for (java.lang.reflect.Field pf : pickerFields) {
                            if (pf.getName().equals("mSelectionDivider")) {
                                pf.setAccessible(true);

                                try {
                                    pf.set(yearNP, new ColorDrawable(ContextCompat.getColor(mainContext,
                                            MainActivity.accentPrimaryColor)));
                                } catch (IllegalArgumentException | IllegalAccessException ignored) {
                                }
                                break;
                                /*} else if(pf.getName().equals("mSelectorWheelPaint")) {
                                   pf.setAccessible(true);
                                        
                                   try {
                                      ((Paint) pf.get(yearNP))
                                            .setColor(getColor(MainActivity.themePrimaryTextColor));
                                   } catch (IllegalArgumentException |
                                         IllegalAccessException ignored) {}*/ //FIXME Doesn't work... yet
                            } else if (pf.getName().equals("mInputText")) {
                                pf.setAccessible(true);

                                try {
                                    ((EditText) pf.get(yearNP)).setTextColor(ContextCompat.getColor(mainContext,
                                            MainActivity.themePrimaryTextColor));
                                } catch (IllegalArgumentException | IllegalAccessException ignored) {
                                }
                            }
                        }

                        yearNP.invalidate();

                        gradesDialogBuilder.setNegativeButton(android.R.string.cancel, null);

                        AlertDialog gradesDialog = gradesDialogBuilder.create();

                        gradesDialog.setCanceledOnTouchOutside(true);
                        gradesDialog.show();

                        gradesDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(
                                ContextCompat.getColor(mainContext, MainActivity.accentSecondaryColor));
                        gradesDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(
                                ContextCompat.getColor(mainContext, MainActivity.accentSecondaryColor));
                    }
                } else {
                    final int databaseFocus = Integer.parseInt(PreferenceManager
                            .getDefaultSharedPreferences(mainContext).getString("pref_grades_term", "1"));

                    if (PreferenceManager.getDefaultSharedPreferences(mainContext).getString("html_grades",
                            null) != null && yearFocus != 0 || termFocus != databaseFocus) {
                        yearFocus = 0;
                        termFocus = databaseFocus;

                        gradesHtml = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("html_grades", null);
                        parseData(HeliniumStudentApp.ACTION_OFFLINE);
                    } else {
                        MainActivity.setUI(HeliniumStudentApp.VIEW_GRADES, HeliniumStudentApp.ACTION_OFFLINE);
                    }
                }
            }
        });

        MainActivity.nextIV.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (MainActivity.isOnline()) {
                    if (termFocus != 4) {
                        termFocus++;

                        getGrades(termFocus, HeliniumStudentApp.df_grades(yearFocus),
                                HeliniumStudentApp.DIREC_NEXT, HeliniumStudentApp.ACTION_REFRESH_IN);
                    } else {
                        MainActivity.setUI(HeliniumStudentApp.VIEW_GRADES, HeliniumStudentApp.ACTION_ONLINE);
                    }
                } else {
                    final int databaseFocus = Integer.parseInt(PreferenceManager
                            .getDefaultSharedPreferences(mainContext).getString("pref_grades_term", "1"));

                    if (PreferenceManager.getDefaultSharedPreferences(mainContext).getString("html_grades",
                            null) != null && yearFocus == 0 && termFocus < databaseFocus) {
                        yearFocus = 0;
                        termFocus = databaseFocus;

                        gradesHtml = PreferenceManager.getDefaultSharedPreferences(mainContext)
                                .getString("html_grades", null);
                        parseData(HeliniumStudentApp.ACTION_OFFLINE);
                    } else {
                        MainActivity.setUI(HeliniumStudentApp.VIEW_GRADES, HeliniumStudentApp.ACTION_OFFLINE);
                    }
                }
            }
        });
    }

    return gradesLayout;
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void sortChannels() {
    ContentResolver cr = getContentResolver();

    StringBuilder where = new StringBuilder(TvBrowserContentProvider.CHANNEL_KEY_SELECTION);
    where.append("=1");

    LinearLayout main = (LinearLayout) getLayoutInflater().inflate(R.layout.channel_sort_list,
            getParentViewGroup(), false);

    Button sortAlphabetically = (Button) main.findViewById(R.id.channel_sort_alpabetically);

    final DynamicListView channelSort = (DynamicListView) main.findViewById(R.id.channel_sort);

    String[] projection = { TvBrowserContentProvider.KEY_ID, TvBrowserContentProvider.CHANNEL_KEY_NAME,
            TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER, TvBrowserContentProvider.CHANNEL_KEY_SELECTION,
            TvBrowserContentProvider.CHANNEL_KEY_LOGO };

    Cursor channels = cr.query(TvBrowserContentProvider.CONTENT_URI_CHANNELS, projection, where.toString(),
            null, TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER);

    final ArrayList<SortInterface> channelSource = new ArrayList<SortInterface>();

    if (channels.moveToFirst()) {
        do {/*from   w ww  .ja  v  a  2s. co m*/
            int key = channels.getInt(0);
            String name = channels.getString(1);

            int order = 0;

            if (!channels.isNull(channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER))) {
                order = channels
                        .getInt(channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER));
            }

            Bitmap channelLogo = UiUtils.createBitmapFromByteArray(
                    channels.getBlob(channels.getColumnIndex(TvBrowserContentProvider.CHANNEL_KEY_LOGO)));

            if (channelLogo != null) {
                BitmapDrawable l = new BitmapDrawable(getResources(), channelLogo);

                ColorDrawable background = new ColorDrawable(SettingConstants.LOGO_BACKGROUND_COLOR);
                background.setBounds(0, 0, channelLogo.getWidth() + 2, channelLogo.getHeight() + 2);

                LayerDrawable logoDrawable = new LayerDrawable(new Drawable[] { background, l });
                logoDrawable.setBounds(background.getBounds());

                l.setBounds(2, 2, channelLogo.getWidth(), channelLogo.getHeight());

                channelLogo = UiUtils.drawableToBitmap(logoDrawable);
            }

            channelSource.add(new ChannelSort(key, name, order, channelLogo));
        } while (channels.moveToNext());

        channels.close();

        final Comparator<SortInterface> sortComparator = new Comparator<SortInterface>() {
            @Override
            public int compare(SortInterface lhs, SortInterface rhs) {
                if (lhs.getSortNumber() < rhs.getSortNumber()) {
                    return -1;
                } else if (lhs.getSortNumber() > rhs.getSortNumber()) {
                    return 1;
                }

                return 0;
            }
        };

        Collections.sort(channelSource, sortComparator);

        // create default logo for channels without logo
        final Bitmap defaultLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

        final StableArrayAdapter<SortInterface> aa = new StableArrayAdapter<SortInterface>(TvBrowser.this,
                R.layout.channel_sort_row, channelSource) {
            public View getView(int position, View convertView, ViewGroup parent) {
                ChannelSort value = (ChannelSort) getItem(position);
                ViewHolder holder = null;

                if (convertView == null) {
                    LayoutInflater mInflater = (LayoutInflater) getContext()
                            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

                    holder = new ViewHolder();

                    convertView = mInflater.inflate(R.layout.channel_sort_row, getParentViewGroup(), false);

                    holder.mTextView = (TextView) convertView.findViewById(R.id.row_of_channel_sort_text);
                    holder.mSortNumber = (TextView) convertView.findViewById(R.id.row_of_channel_sort_number);
                    holder.mLogo = (ImageView) convertView.findViewById(R.id.row_of_channel_sort_icon);

                    convertView.setTag(holder);

                } else {
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.mTextView.setText(value.getName());

                String sortNumber = String.valueOf(value.getSortNumber());

                if (value.getSortNumber() == 0) {
                    sortNumber = "-";
                }

                sortNumber += ".";

                holder.mSortNumber.setText(sortNumber);

                Bitmap logo = value.getLogo();

                if (logo != null) {
                    holder.mLogo.setImageBitmap(logo);
                } else {
                    holder.mLogo.setImageBitmap(defaultLogo);
                }

                return convertView;
            }
        };
        channelSort.setAdapter(aa);
        channelSort.setArrayList(channelSource);
        channelSort.setSortDropListener(new SortDropListener() {
            @Override
            public void dropped(int originalPosition, int position) {
                int startIndex = originalPosition;
                int endIndex = position;

                int droppedPos = position;

                if (originalPosition > position) {
                    startIndex = position;
                    endIndex = originalPosition;
                }

                int previousNumber = 0;

                if (startIndex > 0) {
                    previousNumber = aa.getItem(startIndex - 1).getSortNumber();
                }

                int firstVisible = channelSort.getFirstVisiblePosition();

                for (int i = startIndex; i <= endIndex; i++) {
                    if (i == droppedPos || aa.getItem(i).getSortNumber() != 0) {
                        aa.getItem(i).setSortNumber(++previousNumber);

                        if (i >= firstVisible) {
                            View line = channelSort.getChildAt(i - firstVisible);

                            if (line != null) {
                                ((TextView) line.findViewById(R.id.row_of_channel_sort_number))
                                        .setText(String.valueOf(previousNumber) + ".");
                            }
                        }
                    }
                }

            }
        });

        channelSort.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(final AdapterView<?> adapterView, final View view, final int position,
                    long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

                LinearLayout numberSelection = (LinearLayout) getLayoutInflater()
                        .inflate(R.layout.sort_number_selection, getParentViewGroup(), false);

                mSelectionNumberChanged = false;

                final NumberPicker number = (NumberPicker) numberSelection.findViewById(R.id.sort_picker);
                number.setMinValue(1);
                number.setMaxValue(channelSource.size());
                number.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
                number.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        mSelectionNumberChanged = true;
                    }
                });

                final EditText numberAlternative = (EditText) numberSelection
                        .findViewById(R.id.sort_entered_number);

                builder.setView(numberSelection);

                final ChannelSort selection = (ChannelSort) channelSource.get(position);

                TextView name = (TextView) numberSelection.findViewById(R.id.sort_picker_channel_name);
                name.setText(selection.getName());

                if (selection.getSortNumber() > 0) {
                    if (selection.getSortNumber() < channelSource.size() + 1) {
                        number.setValue(selection.getSortNumber());
                    } else {
                        numberAlternative.setText(String.valueOf(selection.getSortNumber()));
                    }
                }

                builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String test = numberAlternative.getText().toString().trim();

                        if (test.length() == 0 || mSelectionNumberChanged) {
                            selection.setSortNumber(number.getValue());
                        } else {
                            try {
                                selection.setSortNumber(Integer.parseInt(test));
                            } catch (NumberFormatException e1) {
                            }
                        }

                        Collections.sort(channelSource, sortComparator);
                        aa.notifyDataSetChanged();
                    }
                });

                builder.setNegativeButton(android.R.string.cancel, null);

                builder.show();
            }
        });

        sortAlphabetically.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Collections.sort(channelSource, new Comparator<SortInterface>() {
                    @Override
                    public int compare(SortInterface lhs, SortInterface rhs) {
                        return lhs.getName().compareToIgnoreCase(rhs.getName());
                    }
                });

                for (int i = 0; i < channelSource.size(); i++) {
                    channelSource.get(i).setSortNumber(i + 1);
                }

                aa.notifyDataSetChanged();
            }
        });

        AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

        builder.setTitle(R.string.action_sort_channels);
        builder.setView(main);

        builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean somethingChanged = false;

                for (SortInterface selection : channelSource) {
                    if (((ChannelSort) selection).wasChanged()) {
                        somethingChanged = true;

                        ContentValues values = new ContentValues();
                        values.put(TvBrowserContentProvider.CHANNEL_KEY_ORDER_NUMBER,
                                selection.getSortNumber());

                        getContentResolver().update(
                                ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_CHANNELS,
                                        ((ChannelSort) selection).getKey()),
                                values, null, null);
                    }
                }

                if (somethingChanged) {
                    updateProgramListChannelBar();
                }
            }
        });
        builder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builder.show();
    }
}

From source file:com.codename1.impl.android.AndroidImplementation.java

@Override
public Object showNativePicker(final int type, final Component source, final Object currentValue,
        final Object data) {
    if (getActivity() == null) {
        return null;
    }// w  ww  .j  ava 2s  . c  o m
    final boolean[] canceled = new boolean[1];
    final boolean[] dismissed = new boolean[1];

    if (editInProgress()) {
        stopEditing(true);
    }
    if (type == Display.PICKER_TYPE_TIME) {

        class TimePick
                implements TimePickerDialog.OnTimeSetListener, TimePickerDialog.OnCancelListener, Runnable {
            int result = ((Integer) currentValue).intValue();

            public void onTimeSet(TimePicker tp, int hour, int minute) {
                result = hour * 60 + minute;
                dismissed[0] = true;
                synchronized (this) {
                    notify();
                }
            }

            public void run() {
                while (!dismissed[0]) {
                    synchronized (this) {
                        try {
                            wait(50);
                        } catch (InterruptedException er) {
                        }
                    }
                }
            }

            @Override
            public void onCancel(DialogInterface di) {
                dismissed[0] = true;
                canceled[0] = true;
                synchronized (this) {
                    notify();
                }
            }
        }
        final TimePick pickInstance = new TimePick();
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                int hour = ((Integer) currentValue).intValue() / 60;
                int minute = ((Integer) currentValue).intValue() % 60;
                TimePickerDialog tp = new TimePickerDialog(getActivity(), pickInstance, hour, minute, true) {

                    @Override
                    public void cancel() {
                        super.cancel();
                        dismissed[0] = true;
                        canceled[0] = true;
                    }

                    @Override
                    public void dismiss() {
                        super.dismiss();
                        dismissed[0] = true;
                    }

                };
                tp.setOnCancelListener(pickInstance);
                //DateFormat.is24HourFormat(activity));
                tp.show();
            }
        });
        Display.getInstance().invokeAndBlock(pickInstance);
        if (canceled[0]) {
            return null;
        }
        return new Integer(pickInstance.result);
    }
    if (type == Display.PICKER_TYPE_DATE) {
        final java.util.Calendar cl = java.util.Calendar.getInstance();
        if (currentValue != null) {
            cl.setTime((Date) currentValue);
        }
        class DatePick
                implements DatePickerDialog.OnDateSetListener, DatePickerDialog.OnCancelListener, Runnable {
            Date result = (Date) currentValue;

            public void onDateSet(DatePicker dp, int year, int month, int day) {
                java.util.Calendar c = java.util.Calendar.getInstance();
                c.set(java.util.Calendar.YEAR, year);
                c.set(java.util.Calendar.MONTH, month);
                c.set(java.util.Calendar.DAY_OF_MONTH, day);
                result = c.getTime();
                dismissed[0] = true;
                synchronized (this) {
                    notify();
                }
            }

            public void run() {
                while (!dismissed[0]) {
                    synchronized (this) {
                        try {
                            wait(50);
                        } catch (InterruptedException er) {
                        }
                    }
                }
            }

            public void onCancel(DialogInterface di) {
                result = null;
                dismissed[0] = true;
                canceled[0] = true;
                synchronized (this) {
                    notify();
                }
            }
        }
        final DatePick pickInstance = new DatePick();
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                DatePickerDialog tp = new DatePickerDialog(getActivity(), pickInstance,
                        cl.get(java.util.Calendar.YEAR), cl.get(java.util.Calendar.MONTH),
                        cl.get(java.util.Calendar.DAY_OF_MONTH)) {

                    @Override
                    public void cancel() {
                        super.cancel();
                        dismissed[0] = true;
                        canceled[0] = true;
                    }

                    @Override
                    public void dismiss() {
                        super.dismiss();
                        dismissed[0] = true;
                    }

                };
                tp.setOnCancelListener(pickInstance);
                tp.show();
            }
        });
        Display.getInstance().invokeAndBlock(pickInstance);
        return pickInstance.result;
    }
    if (type == Display.PICKER_TYPE_STRINGS) {
        final String[] values = (String[]) data;
        class StringPick implements Runnable, NumberPicker.OnValueChangeListener {
            int result = -1;

            StringPick() {
            }

            public void run() {
                while (!dismissed[0]) {
                    synchronized (this) {
                        try {
                            wait(50);
                        } catch (InterruptedException er) {
                        }
                    }
                }
            }

            public void cancel() {
                dismissed[0] = true;
                canceled[0] = true;
                synchronized (this) {
                    notify();
                }
            }

            public void ok() {
                canceled[0] = false;
                dismissed[0] = true;
                synchronized (this) {
                    notify();
                }
            }

            @Override
            public void onValueChange(NumberPicker np, int oldVal, int newVal) {
                result = newVal;
            }
        }

        final StringPick pickInstance = new StringPick();
        for (int iter = 0; iter < values.length; iter++) {
            if (values[iter].equals(currentValue)) {
                pickInstance.result = iter;
                break;
            }
        }
        if (pickInstance.result == -1 && values.length > 0) {
            // The picker will default to showing the first element anyways
            // If we don't set the result to 0, then the user has to first
            // scroll to a different number, then back to the first option
            // to pick the first option.
            pickInstance.result = 0;
        }

        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                NumberPicker picker = new NumberPicker(getActivity());
                if (source.getClientProperty("showKeyboard") == null) {
                    picker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
                }
                picker.setMinValue(0);
                picker.setMaxValue(values.length - 1);
                picker.setDisplayedValues(values);
                picker.setOnValueChangedListener(pickInstance);
                if (pickInstance.result > -1) {
                    picker.setValue(pickInstance.result);
                }
                RelativeLayout linearLayout = new RelativeLayout(getActivity());
                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(50, 50);
                RelativeLayout.LayoutParams numPicerParams = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                numPicerParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

                linearLayout.setLayoutParams(params);
                linearLayout.addView(picker, numPicerParams);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
                alertDialogBuilder.setView(linearLayout);
                alertDialogBuilder.setCancelable(false)
                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                pickInstance.ok();
                            }
                        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                                pickInstance.cancel();
                            }
                        });
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.show();
            }
        });
        Display.getInstance().invokeAndBlock(pickInstance);
        if (canceled[0]) {
            return null;
        }
        if (pickInstance.result < 0) {
            return null;
        }
        return values[pickInstance.result];
    }
    return null;
}