Example usage for android.widget Spinner setSelection

List of usage examples for android.widget Spinner setSelection

Introduction

In this page you can find the example usage for android.widget Spinner setSelection.

Prototype

@Override
    public void setSelection(int position) 

Source Link

Usage

From source file:ng.uavp.ch.ngusbterminal.SettingsFragment.java

private void SetSpinnerSelection(SharedPreferences sharedPref, Spinner spinner, String key, int defValue) {

    String str = String.valueOf(sharedPref.getInt(key, defValue));

    for (int i = 0; i < spinner.getAdapter().getCount(); i++) {
        String s = spinner.getItemAtPosition(i).toString();
        if (s.equals(str)) {
            spinner.setSelection(i);
            break;
        }/*w ww  .jav  a  2 s  .  co  m*/
    }
}

From source file:com.ntsync.android.sync.activities.ImportActivity.java

public void onLoadFinished(Loader<List<AccountInfo>> loader, List<AccountInfo> data) {
    int bigestAccountIndex = -1;
    int currCount = -1;

    if (sourceAccountAdapter != null) {
        List<AccountInfo> myAccountsData = new ArrayList<AccountInfo>();
        List<AccountInfo> newListData = new ArrayList<AccountInfo>();
        int listPos = 0;
        for (AccountInfo info : data) {
            if (Constants.ACCOUNT_TYPE.equals(info.accountType)) {
                myAccountsData.add(info);
                continue;
            }/*w  w  w  .  jav a 2 s. c  om*/
            if (info.getContactCount() > currCount) {
                currCount = info.getContactCount();
                bigestAccountIndex = listPos;
            }

            newListData.add(info);
            listPos++;
        }
        // If more than one of our accounts is here allow importing to
        // the other
        if (!myAccountsData.isEmpty()) {
            AccountManager accountManager = AccountManager.get(ImportActivity.this);
            Account[] myAccounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
            if (myAccounts.length > 1) {
                for (AccountInfo accountInfo : myAccountsData) {
                    if (accountInfo.getContactCount() > currCount) {
                        currCount = accountInfo.getContactCount();
                        bigestAccountIndex = listPos;
                    }
                    newListData.add(accountInfo);
                    listPos++;
                }
            }
        }

        boolean containsOldData = sourceAccountAdapter.getCount() > 0;
        sourceAccountAdapter.setData(newListData);

        if (bigestAccountIndex >= 0 && !containsOldData) {
            Spinner spinner = (Spinner) findViewById(R.id.sourceAccountSpinner);
            if (spinner != null) {
                spinner.setSelection(bigestAccountIndex);
            }
        }
        updateBtnState();
    }
}

From source file:com.tassadar.multirommgr.installfragment.InstallCard.java

private void restoreInstanceState() {
    CheckBox b = (CheckBox) m_view.findViewById(R.id.install_multirom);
    b.setChecked(m_savedState.getBoolean("install_multirom", b.isChecked()));

    b = (CheckBox) m_view.findViewById(R.id.install_recovery);
    b.setChecked(m_savedState.getBoolean("install_recovery", b.isChecked()));

    b = (CheckBox) m_view.findViewById(R.id.install_kernel);
    String kernel = m_savedState.getString("install_kernel");
    if (kernel != null) {
        if (kernel.equals("false")) {
            b.setChecked(false);/*from  w w w  .j a  va2s . c om*/
        } else {
            b.setChecked(true);
            Spinner s = (Spinner) m_view.findViewById(R.id.kernel_options);
            for (int i = 0; i < s.getAdapter().getCount(); ++i) {
                if (((String) s.getItemAtPosition(i)).equals(kernel)) {
                    s.setSelection(i);
                    break;
                }
            }
        }
    }

    m_savedState = null;
}

From source file:com.esri.arcgisruntime.sample.blendrenderer.ParametersDialogFragment.java

/**
 * Builds parameter dialog with values pulled through from MainActivity.
 *
 * @param savedInstanceState/*from   w w w  .  j a v a  2  s. co  m*/
 * @return create parameter dialog box
 */
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    Bundle blendParameters = getArguments();
    if (blendParameters != null) {
        mAltitude = blendParameters.getInt("altitude");
        mAzimuth = blendParameters.getInt("azimuth");
        mSlopeType = (SlopeType) blendParameters.getSerializable("slope_type");
        mColorRampType = (ColorRamp.PresetType) blendParameters.getSerializable("color_ramp_type");
    }

    final AlertDialog.Builder paramDialog = new AlertDialog.Builder(getContext());
    @SuppressLint("InflateParams")
    View dialogView = inflater.inflate(R.layout.dialog_box, null);
    paramDialog.setView(dialogView);
    paramDialog.setTitle(R.string.dialog_title);
    paramDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dismiss();
        }
    });
    paramDialog.setPositiveButton("Render", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            ParametersListener activity = (ParametersListener) getActivity();
            activity.returnParameters(mAltitude, mAzimuth, mSlopeType, mColorRampType);
        }
    });

    mCurrAltitudeTextView = (TextView) dialogView.findViewById(R.id.curr_altitude_text);
    SeekBar altitudeSeekBar = (SeekBar) dialogView.findViewById(R.id.altitude_seek_bar);
    altitudeSeekBar.setMax(90); //altitude is restricted to 0 - 90
    //set initial altitude value
    updateAltitudeSeekBar(altitudeSeekBar);
    altitudeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            mAltitude = progress;
            updateAltitudeSeekBar(seekBar);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    mCurrAzimuthTextView = (TextView) dialogView.findViewById(R.id.curr_azimuth_text);
    SeekBar azimuthSeekBar = (SeekBar) dialogView.findViewById(R.id.azimuth_seek_bar);
    azimuthSeekBar.setMax(360); //azimuth measured in degrees 0 - 360
    //set initial azimuth value
    updateAzimuthSeekBar(azimuthSeekBar);
    azimuthSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            mAzimuth = progress;
            updateAzimuthSeekBar(seekBar);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });

    List<String> slopeTypeArray = new ArrayList<>();
    slopeTypeArray.add("None"); //ordinals:0
    slopeTypeArray.add("Degree"); //1
    slopeTypeArray.add("Percent rise"); //2
    slopeTypeArray.add("Scaled"); //3

    ArrayAdapter<String> slopeTypeSpinnerAdapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text_view,
            slopeTypeArray);

    Spinner slopeTypeSpinner = (Spinner) dialogView.findViewById(R.id.slope_type_spinner);
    slopeTypeSpinner.setAdapter(slopeTypeSpinnerAdapter);
    slopeTypeSpinner.setSelection(mSlopeType.ordinal());
    slopeTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 0:
                mSlopeType = SlopeType.NONE;
                break;
            case 1:
                mSlopeType = SlopeType.DEGREE;
                break;
            case 2:
                mSlopeType = SlopeType.PERCENT_RISE;
                break;
            case 3:
                mSlopeType = SlopeType.SCALED;
                break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    List<String> colorRampTypeArray = new ArrayList<>();
    colorRampTypeArray.add("None"); //ordinals:0
    colorRampTypeArray.add("Elevation"); //1
    colorRampTypeArray.add("DEM screen"); //2
    colorRampTypeArray.add("DEM light"); //3

    ArrayAdapter<String> colorRampSpinnerAdapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text_view,
            colorRampTypeArray);

    Spinner colorRampSpinner = (Spinner) dialogView.findViewById(R.id.color_ramp_spinner);
    colorRampSpinner.setAdapter(colorRampSpinnerAdapter);
    colorRampSpinner.setSelection(mColorRampType.ordinal());
    colorRampSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {
            case 0:
                mColorRampType = ColorRamp.PresetType.NONE;
                break;
            case 1:
                mColorRampType = ColorRamp.PresetType.ELEVATION;
                break;
            case 2:
                mColorRampType = ColorRamp.PresetType.DEM_SCREEN;
                break;
            case 3:
                mColorRampType = ColorRamp.PresetType.DEM_LIGHT;
                break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    return paramDialog.create();
}

From source file:am.roadpolice.roadpolice.dialogs.DialogSettings.java

private void initUpdateIntervals(final View view) {
    Spinner spinner = (Spinner) view.findViewById(R.id.spinnerUpdateInterval);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.array_update_interval,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);//from   ww  w  .j a  v  a  2  s. c om

    spinner.setSelection(getUpdateInterval(getActivity()));

    // Handle on click selected item listener.
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            mSelectedStateOfUpdateInterval = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
}

From source file:com.uoit.freeroomfinder.FreeRoom.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    // Add the root view container.
    rootView = inflater.inflate(R.layout.activity_free_room, container, false);

    // Load the shared preferences.
    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getActivity().getBaseContext());

    // Get the current date and time.
    curDate = new Date();

    // Set up default values for the display elements in the fragment.

    // Default campus selection.
    Spinner campus = (Spinner) rootView.findViewById(R.id.campus);
    campus.setSelection(Integer.valueOf(sharedPrefs.getString("default_campus", "0")) - 1);

    // Default booking duration.
    Spinner duration = (Spinner) rootView.findViewById(R.id.duration);
    duration.setSelection(Integer.valueOf(sharedPrefs.getString("default_duration", "0")) - 1);

    // Default time selection.
    timeSpinner = (Spinner) rootView.findViewById(R.id.time);
    // Set the current date to show as Today.
    TextView date = (TextView) rootView.findViewById(R.id.date);
    date.setText(DateTimeUtility.formatDate(curDate) + " (Today)");

    datePicked = DateTimeUtility.formatDate(curDate);

    // Instantiate the list of available rooms.
    availableRooms = new ArrayList<Rooms>();

    // Logic for when a date is clicked on. This initiates the custom date spinner control.
    date.setOnClickListener(new OnClickListener() {
        /*//from w w  w .j a v a 2  s .c om
         * (non-Javadoc)
         * 
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            // parse the date that's currently in there.
            Date d = null;
            try {
                d = DateTimeUtility.parseDate(datePicked);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            Calendar c = Calendar.getInstance();
            // Grab the year, month, and day from the spinners.
            if (d != null) {
                c.setTime(d);
            }
            int yy = c.get(Calendar.YEAR);
            int mm = c.get(Calendar.MONTH);
            int dd = c.get(Calendar.DAY_OF_MONTH);

            DatePickerDialog alert = new DatePickerDialog(rootView.getContext(),

                    /**
                     * Set up the listener for when the date is set from the custom spinner alert
                     * dialog.
                     */
                    new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            // Parse the date - year, month, day.
                            datePicked = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                            TextView date = (TextView) rootView.findViewById(R.id.date);

                            // If the date is today's date, set it to Today.
                            date.setText(datePicked);
                            if (datePicked.contains(DateTimeUtility.formatDate(curDate))) {
                                date.setText(datePicked + " (Today)");
                            }
                        }
                    }, yy, mm, dd);

            alert.show();
        }
    });

    // Add the search buttom.
    Button search = (Button) rootView.findViewById(R.id.search);
    search.setOnClickListener(new OnClickListener() {
        /*
         * (non-Javadoc)
         * 
         * @see android.view.View.OnClickListener#onClick(android.view.View)
         */
        @Override
        public void onClick(View v) {
            // When the search button is pressed, fetch the results.
            Date curDate = new Date();

            Spinner timeSpinner = (Spinner) rootView.findViewById(R.id.time);
            Spinner durationSpinner = (Spinner) rootView.findViewById(R.id.duration);
            Spinner campusSpinner = (Spinner) rootView.findViewById(R.id.campus);

            try {
                // Formulate a query based on the time. If we're using the current time, make
                // sure we use the actual current time rather than "Now" because that's invalid.
                if (timeSpinner.getSelectedItem().toString().compareTo("Now") == 0) {
                    timePicked = DateTimeUtility.formatFullTime(DateTimeUtility.formatTime(curDate));
                } else {
                    timePicked = DateTimeUtility.formatFullTime(timeSpinner.getSelectedItem().toString());
                }

                // Add the campus we've selected to the query.
                campusPicked = rootView.getResources().getStringArray(R.array.campus_names)[campusSpinner
                        .getSelectedItemPosition()];

                // Add the duration of the search to the query.
                durationPicked = Integer.valueOf(durationSpinner.getSelectedItem().toString());

                // Formulate the search task.
                ((MainActivity) FreeRoom.this.getActivity()).showProgress(true);
                searchTask = new SearchTask();
                searchTask
                        .setOnFinshedTaskListener((Results) MainActivity.switchTabs(MainActivity.RESULTS_TAB));
                searchTask.execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    return rootView;
}

From source file:fr.eoit.activity.fragment.blueprint.RequiredDecryptorFragment.java

@Override
public void onLoadFinished(Cursor cursor) {
    if (DbUtil.hasAtLeastOneRow(cursor)) {
        String[] from = new String[] { Item.COLUMN_NAME_NAME, "decryptorDesc" };
        int[] to = new int[] { android.R.id.text1, android.R.id.text2 };

        MatrixCursor decryptorCursor = new MatrixCursor(
                new String[] { Item._ID, Item.COLUMN_NAME_NAME, "decryptorDesc" });
        DbUtil.addRowToMatrixCursor(decryptorCursor, 0L, "None", "");

        cursor.moveToFirst();//from   ww w .j av  a  2 s . c  o m
        int selectedItem = 0;
        while (!cursor.isAfterLast()) {
            long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(Item._ID));
            DbUtil.addRowToMatrixCursor(decryptorCursor, itemId,
                    cursor.getString(cursor.getColumnIndexOrThrow(Item.COLUMN_NAME_NAME)),
                    getDecryptorDescription(DecryptorUtil.getDecryptorBonuses(itemId),
                            getActivity().getResources()));

            if (itemId == decryptorId) {
                selectedItem = cursor.getPosition() + 1;
            }

            cursor.moveToNext();
        }

        SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),
                android.R.layout.simple_spinner_item, decryptorCursor, from, to,
                SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        Spinner spinner = (Spinner) getActivity().findViewById(R.id.DECRYPTOR_SPINNER);
        adapter.setDropDownViewResource(R.layout.decryptor_drop_down_item);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new SpinnerDecryptorOnItemSelectedListener());
        spinner.setSelection(selectedItem);
    }
}

From source file:com.enadein.carlogbook.ui.AddUpdateFuelLogActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (loader.getId() == LOADER_TYPE) {
        fuelAdapter.swapCursor(data);/*  ww  w.  j ava 2 s .c o m*/
        long defaultId = DBUtils.getDefaultId(getContentResolver(), ProviderDescriptor.DataValue.Type.FUEL);

        Spinner fuelTypeSpinner = (Spinner) findViewById(R.id.typeSpinner);
        fuelTypeSpinner.setSelection(getPositionFromAdapterById(fuelAdapter, defaultId));

    } else {
        stationAdapter.swapCursor(data);
        long defaultId = DBUtils.getDefaultId(getContentResolver(), ProviderDescriptor.DataValue.Type.STATION);

        Spinner stationSpinner = (Spinner) findViewById(R.id.stationSpinner);
        stationSpinner.setSelection(getPositionFromAdapterById(stationAdapter, defaultId));
    }
}

From source file:nl.jalava.appostle.SortDialog.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.sort_dialog, container, false);

    getDialog().setTitle(getString(R.string.sort_title));

    // Alphabetically or by name.
    final Spinner spinner_types = (Spinner) v.findViewById(R.id.sort_type_spinner);
    ArrayAdapter<CharSequence> adapter_types = ArrayAdapter.createFromResource(getActivity(),
            R.array.sort_types, android.R.layout.simple_spinner_item);
    adapter_types.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner_types.setAdapter(adapter_types);
    spinner_types.setSelection(mSort);

    // Ascending or descending.
    final Spinner spinner_directions = (Spinner) v.findViewById(R.id.sort_direction_spinner);
    ArrayAdapter<CharSequence> adapter_directions = ArrayAdapter.createFromResource(getActivity(),
            R.array.sort_directions, android.R.layout.simple_spinner_item);
    adapter_directions.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner_directions.setAdapter(adapter_directions);
    spinner_directions.setSelection(mDir);

    Button OK_Button = (Button) v.findViewById(R.id.ok_button);
    OK_Button.setOnClickListener(new View.OnClickListener() {
        @Override/*w w  w.  j a  v a 2s. c  o  m*/
        public void onClick(View v) {
            mSort = spinner_types.getSelectedItemPosition();
            mDir = spinner_directions.getSelectedItemPosition();
            SortDialogListener activity = (SortDialogListener) getActivity();
            activity.onFinishSortDialog(mSort, mDir);
            dismiss();
        }
    });

    Button Cancel_Button = (Button) v.findViewById(R.id.cancelButton);
    Cancel_Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });

    return v;
}

From source file:com.github.michalbednarski.intentslab.browser.FetcherOptionsDialog.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Inflate and get views
    LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.browse_components_top_options, null, false);
    mTopLayout = (ViewGroup) view.findViewById(R.id.top_layout);
    Spinner fetcherTypeSpinner = (Spinner) mTopLayout.findViewById(R.id.fetcher_type);
    mTopLayoutWithoutFetcherChildCount = mTopLayout.getChildCount();

    // Prepare fetcher spinner
    fetcherTypeSpinner.setAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,
            FetcherManager.getFetcherNames(getActivity())));
    fetcherTypeSpinner.setSelection(FetcherManager.getFetcherIndex(mFetcher));
    fetcherTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override/* w  w  w. ja v  a2 s . c  o  m*/
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (FetcherManager.getFetcherIndex(mFetcher) != position) {
                mFetcher = FetcherManager.createNewFetcherByIndex(position);
                createFetcherConfigurationView();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Spinner won't have nothing selected
        }
    });

    // Prepare fetcher configuration
    createFetcherConfigurationView();

    // Create dialog
    return new AlertDialog.Builder(getActivity()).setView(view)
            .setPositiveButton(R.string.set_custom_filter, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mFetcher.updateFromConfigurationForm(FetcherOptionsDialog.this);
                    ((BrowseComponentsFragment) getTargetFragment()).setFetcher(mFetcher);
                }
            }).create();
}