Example usage for android.widget ArrayAdapter setDropDownViewResource

List of usage examples for android.widget ArrayAdapter setDropDownViewResource

Introduction

In this page you can find the example usage for android.widget ArrayAdapter setDropDownViewResource.

Prototype

public void setDropDownViewResource(@LayoutRes int resource) 

Source Link

Document

Sets the layout resource to create the drop down views.

Usage

From source file:com.code44.finance.ui.dialogs.recurrencepicker.RecurrencePickerDialogFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    eventBus.register(this);
    mRecurrence.wkst = EventRecurrence.timeDay2Day(Utils.getFirstDayOfWeek(getActivity()));

    getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

    boolean endCountHasFocus = false;
    if (savedInstanceState != null) {
        RecurrenceModel m = (RecurrenceModel) savedInstanceState.get(BUNDLE_MODEL);
        if (m != null) {
            mModel = m;//  w  w w .  j a v  a  2 s.  c o  m
        }
        endCountHasFocus = savedInstanceState.getBoolean(BUNDLE_END_COUNT_HAS_FOCUS);
    } else {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mTime.set(bundle.getLong(BUNDLE_START_TIME_MILLIS));

            String tz = bundle.getString(BUNDLE_TIME_ZONE);
            if (!TextUtils.isEmpty(tz)) {
                mTime.timezone = tz;
            }
            mTime.normalize(false);

            // Time days of week: Sun=0, Mon=1, etc
            mModel.weeklyByDayOfWeek[mTime.weekDay] = true;
            String rrule = bundle.getString(BUNDLE_RRULE);
            if (!TextUtils.isEmpty(rrule)) {
                mModel.recurrenceState = RecurrenceModel.STATE_RECURRENCE;
                mRecurrence.parse(rrule);
                copyEventRecurrenceToModel(mRecurrence, mModel);
                // Leave today's day of week as checked by default in weekly view.
                if (mRecurrence.bydayCount == 0) {
                    mModel.weeklyByDayOfWeek[mTime.weekDay] = true;
                }
            }

            mModel.forceHideSwitchButton = bundle.getBoolean(BUNDLE_HIDE_SWITCH_BUTTON, false);
        } else {
            mTime.setToNow();
        }
    }

    mResources = getResources();
    mView = inflater.inflate(R.layout.recurrencepicker, container, true);

    final Activity activity = getActivity();
    final Configuration config = activity.getResources().getConfiguration();

    mRepeatSwitch = (SwitchCompat) mView.findViewById(R.id.repeat_switch);
    if (mModel.forceHideSwitchButton) {
        mRepeatSwitch.setChecked(true);
        mRepeatSwitch.setVisibility(View.GONE);
        mModel.recurrenceState = RecurrenceModel.STATE_RECURRENCE;
    } else {
        mRepeatSwitch.setChecked(mModel.recurrenceState == RecurrenceModel.STATE_RECURRENCE);
        mRepeatSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mModel.recurrenceState = isChecked ? RecurrenceModel.STATE_RECURRENCE
                        : RecurrenceModel.STATE_NO_RECURRENCE;
                togglePickerOptions();
            }
        });
    }
    mFreqSpinner = (Spinner) mView.findViewById(R.id.freqSpinner);
    mFreqSpinner.setOnItemSelectedListener(this);
    ArrayAdapter<CharSequence> freqAdapter = ArrayAdapter.createFromResource(getActivity(),
            R.array.recurrence_freq, R.layout.recurrencepicker_freq_item);
    freqAdapter.setDropDownViewResource(R.layout.recurrencepicker_freq_item);
    mFreqSpinner.setAdapter(freqAdapter);

    mIntervalGroup = (LinearLayout) mView.findViewById(R.id.intervalGroup);
    mInterval = (EditText) mView.findViewById(R.id.interval);
    mInterval.addTextChangedListener(new minMaxTextWatcher(1, INTERVAL_DEFAULT, INTERVAL_MAX) {
        @Override
        void onChange(int v) {
            if (mIntervalResId != -1 && mInterval.getText().toString().length() > 0) {
                mModel.interval = v;
                updateIntervalText();
                mInterval.requestLayout();
            }
        }
    });
    mIntervalPreText = (TextView) mView.findViewById(R.id.intervalPreText);
    mIntervalPostText = (TextView) mView.findViewById(R.id.intervalPostText);

    mStartDatePreText = (TextView) mView.findViewById(R.id.startDatePreText);
    mStartDateTextView = (TextView) mView.findViewById(R.id.startDate);
    mStartDateTextView.setOnClickListener(this);
    if (mModel.startDate == null) {
        mModel.startDate = new Time(mTime);
        mModel.startDate.normalize(false);
    }

    mEndGroup = (LinearLayout) mView.findViewById(R.id.endGroup);
    mEndNeverStr = mResources.getString(R.string.recurrence_end_continously);
    mEndDateLabel = mResources.getString(R.string.recurrence_end_date_label);
    mEndCountLabel = mResources.getString(R.string.recurrence_end_count_label);

    mEndSpinnerArray.add(mEndNeverStr);
    mEndSpinnerArray.add(mEndDateLabel);
    mEndSpinnerArray.add(mEndCountLabel);
    mEndSpinner = (Spinner) mView.findViewById(R.id.endSpinner);
    mEndSpinner.setOnItemSelectedListener(this);
    mEndSpinnerAdapter = new EndSpinnerAdapter(getActivity(), mEndSpinnerArray,
            R.layout.recurrencepicker_freq_item, R.layout.recurrencepicker_end_text);
    mEndSpinnerAdapter.setDropDownViewResource(R.layout.recurrencepicker_freq_item);
    mEndSpinner.setAdapter(mEndSpinnerAdapter);

    mEndCount = (EditText) mView.findViewById(R.id.endCount);
    mEndCount.addTextChangedListener(new minMaxTextWatcher(1, COUNT_DEFAULT, COUNT_MAX) {
        @Override
        void onChange(int v) {
            if (mModel.endCount != v) {
                mModel.endCount = v;
                updateEndCountText();
                mEndCount.requestLayout();
            }
        }
    });
    mPostEndCount = (TextView) mView.findViewById(R.id.postEndCount);

    mEndDateTextView = (TextView) mView.findViewById(R.id.endDate);
    mEndDateTextView.setOnClickListener(this);
    if (mModel.endDate == null) {
        mModel.endDate = new Time(mTime);
        switch (mModel.freq) {
        case RecurrenceModel.FREQ_DAILY:
        case RecurrenceModel.FREQ_WEEKLY:
            mModel.endDate.month += 1;
            break;
        case RecurrenceModel.FREQ_MONTHLY:
            mModel.endDate.month += 3;
            break;
        case RecurrenceModel.FREQ_YEARLY:
            mModel.endDate.year += 3;
            break;
        }
        mModel.endDate.normalize(false);
    }

    mWeekGroup = (LinearLayout) mView.findViewById(R.id.weekGroup);
    mWeekGroup2 = (LinearLayout) mView.findViewById(R.id.weekGroup2);

    // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7
    String[] dayOfWeekString = new DateFormatSymbols().getWeekdays();

    mMonthRepeatByDayOfWeekStrs = new String[7][];
    // from Time.SUNDAY as 0 through Time.SATURDAY as 6
    mMonthRepeatByDayOfWeekStrs[0] = mResources.getStringArray(R.array.repeat_by_nth_sun);
    mMonthRepeatByDayOfWeekStrs[1] = mResources.getStringArray(R.array.repeat_by_nth_mon);
    mMonthRepeatByDayOfWeekStrs[2] = mResources.getStringArray(R.array.repeat_by_nth_tues);
    mMonthRepeatByDayOfWeekStrs[3] = mResources.getStringArray(R.array.repeat_by_nth_wed);
    mMonthRepeatByDayOfWeekStrs[4] = mResources.getStringArray(R.array.repeat_by_nth_thurs);
    mMonthRepeatByDayOfWeekStrs[5] = mResources.getStringArray(R.array.repeat_by_nth_fri);
    mMonthRepeatByDayOfWeekStrs[6] = mResources.getStringArray(R.array.repeat_by_nth_sat);

    // In Time.java day of week order e.g. Sun = 0
    int idx = Utils.getFirstDayOfWeek(getActivity());

    // In Calendar.java day of week order e.g Sun = 1 ... Sat = 7
    dayOfWeekString = new DateFormatSymbols().getShortWeekdays();

    int numOfButtonsInRow1;
    int numOfButtonsInRow2;

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
        // Get screen width in dp first
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);

        float density = getResources().getDisplayMetrics().density;
        float dpWidth = outMetrics.widthPixels / density;
        if (dpWidth > MIN_SCREEN_WIDTH_FOR_SINGLE_ROW_WEEK) {
            numOfButtonsInRow1 = 7;
            numOfButtonsInRow2 = 0;
            mWeekGroup2.setVisibility(View.GONE);
            mWeekGroup2.getChildAt(3).setVisibility(View.GONE);
        } else {
            numOfButtonsInRow1 = 4;
            numOfButtonsInRow2 = 3;

            mWeekGroup2.setVisibility(View.VISIBLE);
            // Set rightmost button on the second row invisible so it takes up
            // space and everything centers properly
            mWeekGroup2.getChildAt(3).setVisibility(View.INVISIBLE);
        }
    } else if (mResources.getConfiguration().screenWidthDp > MIN_SCREEN_WIDTH_FOR_SINGLE_ROW_WEEK) {
        numOfButtonsInRow1 = 7;
        numOfButtonsInRow2 = 0;
        mWeekGroup2.setVisibility(View.GONE);
        mWeekGroup2.getChildAt(3).setVisibility(View.GONE);
    } else {
        numOfButtonsInRow1 = 4;
        numOfButtonsInRow2 = 3;

        mWeekGroup2.setVisibility(View.VISIBLE);
        // Set rightmost button on the second row invisible so it takes up
        // space and everything centers properly
        mWeekGroup2.getChildAt(3).setVisibility(View.INVISIBLE);
    }

    /* First row */
    for (int i = 0; i < 7; i++) {
        if (i >= numOfButtonsInRow1) {
            mWeekGroup.getChildAt(i).setVisibility(View.GONE);
            continue;
        }

        mWeekByDayButtons[idx] = (ToggleButton) mWeekGroup.getChildAt(i);
        mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
        mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
        mWeekByDayButtons[idx].setOnCheckedChangeListener(this);

        if (++idx >= 7) {
            idx = 0;
        }
    }

    /* 2nd Row */
    for (int i = 0; i < 3; i++) {
        if (i >= numOfButtonsInRow2) {
            mWeekGroup2.getChildAt(i).setVisibility(View.GONE);
            continue;
        }
        mWeekByDayButtons[idx] = (ToggleButton) mWeekGroup2.getChildAt(i);
        mWeekByDayButtons[idx].setTextOff(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
        mWeekByDayButtons[idx].setTextOn(dayOfWeekString[TIME_DAY_TO_CALENDAR_DAY[idx]]);
        mWeekByDayButtons[idx].setOnCheckedChangeListener(this);

        if (++idx >= 7) {
            idx = 0;
        }
    }

    mMonthGroup = (LinearLayout) mView.findViewById(R.id.monthGroup);
    mMonthRepeatByRadioGroup = (RadioGroup) mView.findViewById(R.id.monthGroup);
    mMonthRepeatByRadioGroup.setOnCheckedChangeListener(this);
    mRepeatMonthlyByNthDayOfWeek = (RadioButton) mView.findViewById(R.id.repeatMonthlyByNthDayOfTheWeek);
    mRepeatMonthlyByNthDayOfMonth = (RadioButton) mView.findViewById(R.id.repeatMonthlyByNthDayOfMonth);

    mDoneButton = (Button) mView.findViewById(R.id.done_button);
    mDoneButton.setOnClickListener(this);

    Button cancelButton = (Button) mView.findViewById(R.id.cancel_button);
    //FIXME no text color for this one ?
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dismiss();
        }
    });

    togglePickerOptions();
    updateDialog();
    if (endCountHasFocus) {
        mEndCount.requestFocus();
    }
    return mView;
}

From source file:com.mantz_it.rfanalyzer.ui.activity.MainActivity.java

public void showRecordingDialog() {
    if (!running || scheduler == null || demodulator == null || source == null) {
        toaster.showLong("Analyzer must be running to start recording");
        return;//  ww w  .  j  av a 2 s  . com
    }
    // Check for the WRITE_EXTERNAL_STORAGE permission:
    if (ContextCompat.checkSelfPermission(this,
            "android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[] { "android.permission.WRITE_EXTERNAL_STORAGE" },
                PERMISSION_REQUEST_RECORDING_WRITE_FILES);
        return; // wait for the permission response (handled in onRequestPermissionResult())
    }

    final String externalDir = Environment.getExternalStorageDirectory().getAbsolutePath();
    final int[] supportedSampleRates = rxSampleRate.getSupportedSampleRates();
    final double maxFreqMHz = rxFrequency.getMax() / 1000000f; // max frequency of the source in MHz
    final int sourceType = Integer.parseInt(preferences.getString(getString(R.string.pref_sourceType), "1"));
    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.US);

    // Get references to the GUI components:
    final ScrollView view = (ScrollView) this.getLayoutInflater().inflate(R.layout.start_recording, null);
    final EditText et_filename = (EditText) view.findViewById(R.id.et_recording_filename);
    final EditText et_frequency = (EditText) view.findViewById(R.id.et_recording_frequency);
    final Spinner sp_sampleRate = (Spinner) view.findViewById(R.id.sp_recording_sampleRate);
    final TextView tv_fixedSampleRateHint = (TextView) view.findViewById(R.id.tv_recording_fixedSampleRateHint);
    final CheckBox cb_stopAfter = (CheckBox) view.findViewById(R.id.cb_recording_stopAfter);
    final EditText et_stopAfter = (EditText) view.findViewById(R.id.et_recording_stopAfter);
    final Spinner sp_stopAfter = (Spinner) view.findViewById(R.id.sp_recording_stopAfter);

    // Setup the sample rate spinner:
    final ArrayAdapter<Integer> sampleRateAdapter = new ArrayAdapter<>(this,
            android.R.layout.simple_list_item_1);
    for (int sampR : supportedSampleRates)
        sampleRateAdapter.add(sampR);
    sampleRateAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp_sampleRate.setAdapter(sampleRateAdapter);

    // Add listener to the frequency textfield, the sample rate spinner and the checkbox:
    et_frequency.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (et_frequency.getText().length() == 0)
                return;
            double freq = Double.parseDouble(et_frequency.getText().toString());
            if (freq < maxFreqMHz)
                freq = freq * 1000000;
            et_filename.setText(simpleDateFormat.format(new Date()) + "_" + SOURCE_NAMES[sourceType] + "_"
                    + (long) freq + "Hz_" + sp_sampleRate.getSelectedItem() + "Sps.iq");
        }
    });
    sp_sampleRate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (et_frequency.getText().length() == 0)
                return;
            double freq = Double.parseDouble(et_frequency.getText().toString());
            if (freq < maxFreqMHz)
                freq = freq * 1000000;
            et_filename.setText(simpleDateFormat.format(new Date()) + "_" + SOURCE_NAMES[sourceType] + "_"
                    + (long) freq + "Hz_" + sp_sampleRate.getSelectedItem() + "Sps.iq");
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    cb_stopAfter.setOnCheckedChangeListener((buttonView, isChecked) -> {
        et_stopAfter.setEnabled(isChecked);
        sp_stopAfter.setEnabled(isChecked);
    });

    // Set default frequency, sample rate and stop after values:
    et_frequency.setText(Long.toString(analyzerSurface.getVirtualFrequency()));
    int sampleRateIndex = 0;
    int lastSampleRate = preferences.getInt(getString(R.string.pref_recordingSampleRate), 1000000);
    for (; sampleRateIndex < supportedSampleRates.length; sampleRateIndex++) {
        if (supportedSampleRates[sampleRateIndex] >= lastSampleRate)
            break;
    }
    if (sampleRateIndex >= supportedSampleRates.length)
        sampleRateIndex = supportedSampleRates.length - 1;
    sp_sampleRate.setSelection(sampleRateIndex);
    cb_stopAfter.toggle(); // just to trigger the listener at least once!
    cb_stopAfter.setChecked(preferences.getBoolean(getString(R.string.pref_recordingStopAfterEnabled), false));
    et_stopAfter.setText(
            Integer.toString(preferences.getInt(getString(R.string.pref_recordingStopAfterValue), 10)));
    sp_stopAfter.setSelection(preferences.getInt(getString(R.string.pref_recordingStopAfterUnit), 0));

    // disable sample rate selection if demodulation is running:
    if (demodulationMode != Demodulator.DEMODULATION_OFF) {
        sampleRateAdapter.add(rxSampleRate.get()); // add the current sample rate in case it's not already in the list
        sp_sampleRate.setSelection(sampleRateAdapter.getPosition(rxSampleRate.get())); // select it
        sp_sampleRate.setEnabled(false); // disable the spinner
        tv_fixedSampleRateHint.setVisibility(View.VISIBLE);
    }

    // Show dialog:
    new AlertDialog.Builder(this).setTitle("Start recording").setView(view)
            .setPositiveButton("Record", (dialog, whichButton) -> {
                String filename = et_filename.getText().toString();
                final int stopAfterUnit = sp_stopAfter.getSelectedItemPosition();
                final int stopAfterValue = Integer.parseInt(et_stopAfter.getText().toString());
                //todo check filename

                // Set the frequency in the source:
                if (et_frequency.getText().length() == 0)
                    return;
                double freq = Double.parseDouble(et_frequency.getText().toString());
                if (freq < maxFreqMHz)
                    freq = freq * 1000000;
                if (freq <= rxFrequency.getMax() && freq >= rxFrequency.getMin())
                    rxFrequency.set((long) freq);
                else {
                    toaster.showLong("Frequency is invalid!");
                    return;
                }

                // Set the sample rate (only if demodulator is off):
                if (demodulationMode == Demodulator.DEMODULATION_OFF)
                    rxSampleRate.set((Integer) sp_sampleRate.getSelectedItem());

                // Open file and start recording:
                recordingFile = new File(externalDir + "/" + RECORDING_DIR + "/" + filename);
                recordingFile.getParentFile().mkdir(); // Create directory if it does not yet exist
                try {
                    scheduler.startRecording(new BufferedOutputStream(new FileOutputStream(recordingFile)));
                } catch (FileNotFoundException e) {
                    Log.e(LOGTAG, "showRecordingDialog: File not found: " + recordingFile.getAbsolutePath());
                }

                // safe preferences:
                SharedPreferences.Editor edit = preferences.edit();
                edit.putInt(getString(R.string.pref_recordingSampleRate),
                        (Integer) sp_sampleRate.getSelectedItem());
                edit.putBoolean(getString(R.string.pref_recordingStopAfterEnabled), cb_stopAfter.isChecked());
                edit.putInt(getString(R.string.pref_recordingStopAfterValue), stopAfterValue);
                edit.putInt(getString(R.string.pref_recordingStopAfterUnit), stopAfterUnit);
                edit.apply();

                analyzerSurface.setRecordingEnabled(true);

                updateActionBar();

                // if stopAfter was selected, start thread to supervise the recording:
                if (cb_stopAfter.isChecked()) {
                    final String recorderSuperviserName = "Supervisor Thread";
                    Thread supervisorThread = new Thread(() -> {
                        Log.i(LOGTAG, "recording_superviser: Supervisor Thread started. (Thread: "
                                + recorderSuperviserName + ")");
                        try {
                            long startTime = System.currentTimeMillis();
                            boolean stop = false;

                            // We check once per half a second if the stop criteria is met:
                            Thread.sleep(500);
                            while (recordingFile != null && !stop) {
                                switch (stopAfterUnit) { // see arrays.xml - recording_stopAfterUnit
                                case 0: /* MB */
                                    if (recordingFile.length() / 1000000 >= stopAfterValue)
                                        stop = true;
                                    break;
                                case 1: /* GB */
                                    if (recordingFile.length() / 1000000000 >= stopAfterValue)
                                        stop = true;
                                    break;
                                case 2: /* sec */
                                    if (System.currentTimeMillis() - startTime >= stopAfterValue * 1000)
                                        stop = true;
                                    break;
                                case 3: /* min */
                                    if (System.currentTimeMillis() - startTime >= stopAfterValue * 1000 * 60)
                                        stop = true;
                                    break;
                                }
                            }
                            // stop recording:
                            stopRecording();
                        } catch (InterruptedException e) {
                            // todo: shouldn't we call stopRecording() here? how about finally{}?
                            Log.e(LOGTAG, "recording_superviser: Interrupted!");
                        } catch (NullPointerException e) {
                            Log.e(LOGTAG, "recording_superviser: Recording file is null!");
                        }
                        Log.i(LOGTAG, "recording_superviser: Supervisor Thread stopped. (Thread: "
                                + recorderSuperviserName + ")");

                    }, recorderSuperviserName);
                    supervisorThread.start();
                }
            }).setNegativeButton("Cancel", (dialog, whichButton) -> {
                // do nothing
            }).show().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}

From source file:com.github.akinaru.hcidebugger.activity.HciDebuggerActivity.java

/**
 * setup filter spinner//from   w w w .  ja v a 2  s .com
 *
 * @param ressourceId
 * @param view
 * @param spinnerId
 * @param value
 */
private void setupSpinnerAdapter(final int ressourceId, final View view, int spinnerId, String value) {

    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(HciDebuggerActivity.this, ressourceId,
            android.R.layout.simple_spinner_item);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    final Spinner sItems = (Spinner) view.findViewById(spinnerId);
    sItems.setAdapter(adapter);

    sItems.setSelection(getIndex(sItems, value));

    sItems.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view2, int position, long id) {

            if (!sItems.getSelectedItem().toString().equals(getResources().getString(R.string.filter_choose))) {

                SharedPreferences.Editor editor = prefs.edit();

                if (ressourceId == R.array.packet_type_array) {

                    if (sItems.getSelectedItem().toString().equals(Constants.HCI_EVENT)) {
                        displayEventSpinner(view);
                    } else {
                        displayCmdSpinner(view);
                    }
                    filters.setPacketType(sItems.getSelectedItem().toString());

                    editor.putString(Constants.PREFERENCES_PACKET_TYPE_FILTER,
                            sItems.getSelectedItem().toString());
                    editor.commit();

                } else if (ressourceId == R.array.event_type_array) {

                    if (sItems.getSelectedItem().toString().equals(Constants.HCI_LE_META)) {
                        displaySubEventSpinner(view);
                    }

                    filters.setEventType(sItems.getSelectedItem().toString());

                    editor.putString(Constants.PREFERENCES_EVENT_TYPE_FILTER,
                            sItems.getSelectedItem().toString());
                    editor.commit();

                } else if (ressourceId == R.array.ogf_array) {

                    filters.setOgf(sItems.getSelectedItem().toString());

                    editor.putString(Constants.PREFERENCES_OGF_FILTER, sItems.getSelectedItem().toString());
                    editor.commit();

                } else if (ressourceId == R.array.subevent_array) {

                    if (sItems.getSelectedItem().toString().equals(Constants.HCI_ADVERTISING_REPORT)) {
                        displayAdvertizingReportFilter(view);
                    }

                    filters.setSubEventType(sItems.getSelectedItem().toString());

                    editor.putString(Constants.PREFERENCES_SUBEVENT_FILTERS,
                            sItems.getSelectedItem().toString());
                    editor.commit();
                }
            }
        }

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

        }
    });
}

From source file:com.ichi2.anki.NoteEditor.java

@Override
protected void onCollectionLoaded(Collection col) {
    super.onCollectionLoaded(col);
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    Intent intent = getIntent();/*from  w  w  w.j ava 2s .c om*/
    Timber.d("onCollectionLoaded: caller: %d", mCaller);

    SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(getBaseContext());

    registerExternalStorageListener();

    View mainView = findViewById(android.R.id.content);

    Toolbar toolbar = (Toolbar) mainView.findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
    }

    mFieldsLayoutContainer = (LinearLayout) findViewById(R.id.CardEditorEditFieldsLayout);

    mTagsButton = (TextView) findViewById(R.id.CardEditorTagText);
    mCardsButton = (TextView) findViewById(R.id.CardEditorCardsText);
    mCardsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Timber.i("NoteEditor:: Cards button pressed. Opening template editor");
            showCardTemplateEditor();
        }
    });

    Preferences.COMING_FROM_ADD = false;

    mAedictIntent = false;

    switch (mCaller) {
    case CALLER_NOCALLER:
        Timber.e("no caller could be identified, closing");
        finishWithoutAnimation();
        return;

    case CALLER_REVIEWER:
        mCurrentEditedCard = AbstractFlashcardViewer.getEditorCard();
        if (mCurrentEditedCard == null) {
            finishWithoutAnimation();
            return;
        }
        mEditorNote = mCurrentEditedCard.note();
        mAddNote = false;
        break;

    case CALLER_STUDYOPTIONS:
    case CALLER_DECKPICKER:
        mAddNote = true;
        break;

    case CALLER_CARDBROWSER_EDIT:
        mCurrentEditedCard = CardBrowser.sCardBrowserCard;
        if (mCurrentEditedCard == null) {
            finishWithoutAnimation();
            return;
        }
        mEditorNote = mCurrentEditedCard.note();
        mAddNote = false;
        break;

    case CALLER_CARDBROWSER_ADD:
        mAddNote = true;
        break;

    case CALLER_CARDEDITOR:
        mAddNote = true;
        break;

    case CALLER_CARDEDITOR_INTENT_ADD:
        fetchIntentInformation(intent);
        if (mSourceText == null) {
            finishWithoutAnimation();
            return;
        }
        if (mSourceText[0].equals("Aedict Notepad") && addFromAedict(mSourceText[1])) {
            finishWithoutAnimation();
            return;
        }
        mAddNote = true;
        break;
    }

    // Note type Selector
    mNoteTypeSpinner = (Spinner) findViewById(R.id.note_type_spinner);
    mAllModelIds = new ArrayList<Long>();
    final ArrayList<String> modelNames = new ArrayList<String>();
    ArrayList<JSONObject> models = getCol().getModels().all();
    Collections.sort(models, new JSONNameComparator());
    for (JSONObject m : models) {
        try {
            modelNames.add(m.getString("name"));
            mAllModelIds.add(m.getLong("id"));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    ArrayAdapter<String> noteTypeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            modelNames);
    mNoteTypeSpinner.setAdapter(noteTypeAdapter);
    noteTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Deck Selector
    TextView deckTextView = (TextView) findViewById(R.id.CardEditorDeckText);
    // If edit mode and more than one card template distinguish between "Deck" and "Card deck"
    try {
        if (!mAddNote && mEditorNote.model().getJSONArray("tmpls").length() > 1) {
            deckTextView.setText(R.string.CardEditorCardDeck);
        }
    } catch (JSONException e1) {
        throw new RuntimeException();
    }
    mNoteDeckSpinner = (Spinner) findViewById(R.id.note_deck_spinner);
    mAllDeckIds = new ArrayList<Long>();
    final ArrayList<String> deckNames = new ArrayList<String>();

    ArrayList<JSONObject> decks = getCol().getDecks().all();
    Collections.sort(decks, new JSONNameComparator());
    for (JSONObject d : decks) {
        try {
            // add current deck and all other non-filtered decks to deck list
            long thisDid = d.getLong("id");
            long currentDid = getCol().getDecks().current().getLong("id");
            if (d.getInt("dyn") == 0 || (!mAddNote && thisDid == currentDid)) {
                deckNames.add(d.getString("name"));
                mAllDeckIds.add(thisDid);
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    ArrayAdapter<String> noteDeckAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            deckNames);
    mNoteDeckSpinner.setAdapter(noteDeckAdapter);
    noteDeckAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mNoteDeckSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // Timber.i("NoteEditor:: onItemSelected() fired on mNoteDeckSpinner with pos = "+Integer.toString(pos));
            mCurrentDid = mAllDeckIds.get(pos);
        }

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

    setDid(mEditorNote);

    setNote(mEditorNote);

    // Set current note type and deck positions in spinners
    int position;
    try {
        position = mAllModelIds.indexOf(mEditorNote.model().getLong("id"));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    // set selection without firing selectionChanged event
    // nb: setOnItemSelectedListener needs to occur after this
    mNoteTypeSpinner.setSelection(position, false);

    if (mAddNote) {
        mNoteTypeSpinner.setOnItemSelectedListener(new SetNoteTypeListener());
        setTitle(R.string.cardeditor_title_add_note);
        // set information transferred by intent
        String contents = null;
        if (mSourceText != null) {
            if (mAedictIntent && (mEditFields.size() == 3) && mSourceText[1].contains("[")) {
                contents = mSourceText[1].replaceFirst("\\[", "\u001f" + mSourceText[0] + "\u001f");
                contents = contents.substring(0, contents.length() - 1);
            } else if (mEditFields.size() > 0) {
                mEditFields.get(0).setText(mSourceText[0]);
                if (mEditFields.size() > 1) {
                    mEditFields.get(1).setText(mSourceText[1]);
                }
            }
        } else {
            contents = intent.getStringExtra(EXTRA_CONTENTS);
        }
        if (contents != null) {
            setEditFieldTexts(contents);
        }
    } else {
        mNoteTypeSpinner.setOnItemSelectedListener(new EditNoteTypeListener());
        setTitle(R.string.cardeditor_title_edit_card);
    }

    ((LinearLayout) findViewById(R.id.CardEditorTagButton)).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Timber.i("NoteEditor:: Tags button pressed... opening tags editor");
            showTagsDialog();
        }
    });

    if (!mAddNote && mCurrentEditedCard != null) {
        Timber.i("NoteEditor:: Edit note activity successfully started with card id %d",
                mCurrentEditedCard.getId());
    }
}

From source file:com.cypress.cysmart.BLEServiceFragments.SensorHubService.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.sensor_hub, container, false);
    LinearLayout parent = (LinearLayout) rootView.findViewById(R.id.parent_sensorhub);
    parent.setOnClickListener(new OnClickListener() {

        @Override/*w  w  w. java  2s.  co m*/
        public void onClick(View v) {

        }
    });
    accX = (TextView) rootView.findViewById(R.id.acc_x_value);
    accY = (TextView) rootView.findViewById(R.id.acc_y_value);
    accZ = (TextView) rootView.findViewById(R.id.acc_z_value);
    BAT = (TextView) rootView.findViewById(R.id.bat_value);
    STEMP = (TextView) rootView.findViewById(R.id.temp_value);
    mProgressDialog = new ProgressDialog(getActivity());
    Spressure = (TextView) rootView.findViewById(R.id.pressure_value);

    // Locate device button listener
    Button locateDevice = (Button) rootView.findViewById(R.id.locate_device);
    locateDevice.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Button btn = (Button) v;
            String buttonText = btn.getText().toString();
            String startText = getResources().getString(R.string.sen_hub_locate);
            String stopText = getResources().getString(R.string.sen_hub_locate_stop);
            if (buttonText.equalsIgnoreCase(startText)) {
                btn.setText(stopText);
                if (mWriteAlertCharacteristic != null) {
                    byte[] convertedBytes = convertingTobyteArray(IMM_HIGH_ALERT);
                    BluetoothLeService.writeCharacteristicNoresponse(mWriteAlertCharacteristic, convertedBytes);
                }

            } else {
                btn.setText(startText);
                if (mWriteAlertCharacteristic != null) {
                    byte[] convertedBytes = convertingTobyteArray(IMM_NO_ALERT);
                    BluetoothLeService.writeCharacteristicNoresponse(mWriteAlertCharacteristic, convertedBytes);
                }
            }

        }
    });
    final ImageButton acc_more = (ImageButton) rootView.findViewById(R.id.acc_more);
    final ImageButton stemp_more = (ImageButton) rootView.findViewById(R.id.stemp_more);
    final ImageButton spressure_more = (ImageButton) rootView.findViewById(R.id.spressure_more);

    final LinearLayout acc_layLayout = (LinearLayout) rootView.findViewById(R.id.acc_context_menu);
    final LinearLayout stemp_layLayout = (LinearLayout) rootView.findViewById(R.id.stemp_context_menu);
    final LinearLayout spressure_layLayout = (LinearLayout) rootView.findViewById(R.id.spressure_context_menu);

    // expand listener
    acc_more.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (acc_layLayout.getVisibility() != View.VISIBLE) {
                acc_more.setRotation(90);
                CustomSlideAnimation a = new CustomSlideAnimation(acc_layLayout, CustomSlideAnimation.EXPAND);
                a.setHeight(height);
                acc_layLayout.startAnimation(a);
                acc_scan_interval = (EditText) rootView.findViewById(R.id.acc_sensor_scan_interval);
                if (ACCSensorScanCharacteristic != null) {
                    acc_scan_interval.setText(ACCSensorScanCharacteristic);
                }
                acc_sensortype = (TextView) rootView.findViewById(R.id.acc_sensor_type);
                if (ACCSensorTypeCharacteristic != null) {
                    acc_sensortype.setText(ACCSensorTypeCharacteristic);
                }
                acc_scan_interval.setOnEditorActionListener(new OnEditorActionListener() {

                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            int myNum = 0;

                            try {
                                myNum = Integer.parseInt(acc_scan_interval.getText().toString());
                            } catch (NumberFormatException nfe) {
                                nfe.printStackTrace();
                            }
                            byte[] convertedBytes = convertingTobyteArray(Integer.toString(myNum));
                            BluetoothLeService.writeCharacteristicNoresponse(mReadACCSensorScanCharacteristic,
                                    convertedBytes);
                        }
                        return false;
                    }
                });
                Spinner spinner_filterconfiguration = (Spinner) rootView
                        .findViewById(R.id.acc_filter_configuration);
                // Create an ArrayAdapter using the string array and a
                // default
                // spinner layout
                ArrayAdapter<CharSequence> adapter_filterconfiguration = ArrayAdapter.createFromResource(
                        getActivity(), R.array.filter_configuration_alert_array,
                        android.R.layout.simple_spinner_item);
                // Specify the layout to use when the list of choices
                // appears
                adapter_filterconfiguration
                        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                // Apply the adapter to the spinner
                spinner_filterconfiguration.setAdapter(adapter_filterconfiguration);

            } else {
                acc_more.setRotation(-90);

                acc_scan_interval.setText("");
                acc_sensortype.setText("");
                CustomSlideAnimation a = new CustomSlideAnimation(acc_layLayout, CustomSlideAnimation.COLLAPSE);
                height = a.getHeight();
                acc_layLayout.startAnimation(a);
            }
        }
    });
    // expand listener
    stemp_more.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            if (stemp_layLayout.getVisibility() != View.VISIBLE) {
                stemp_more.setRotation(90);
                CustomSlideAnimation a = new CustomSlideAnimation(stemp_layLayout, CustomSlideAnimation.EXPAND);
                a.setHeight(height);
                stemp_layLayout.startAnimation(a);
                stemp_scan_interval = (EditText) rootView.findViewById(R.id.stemp_sensor_scan_interval);
                if (STEMPSensorScanCharacteristic != null) {
                    stemp_scan_interval.setText(STEMPSensorScanCharacteristic);
                }
                stemp_sensortype = (TextView) rootView.findViewById(R.id.stemp_sensor_type);
                if (STEMPSensorTypeCharacteristic != null) {
                    stemp_sensortype.setText(STEMPSensorTypeCharacteristic);
                }
                stemp_scan_interval.setOnEditorActionListener(new OnEditorActionListener() {

                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            int myNum = 0;

                            try {
                                myNum = Integer.parseInt(stemp_scan_interval.getText().toString());
                            } catch (NumberFormatException nfe) {
                                nfe.printStackTrace();
                            }
                            byte[] convertedBytes = convertingTobyteArray(Integer.toString(myNum));
                            BluetoothLeService.writeCharacteristicNoresponse(mReadSTEMPSensorScanCharacteristic,
                                    convertedBytes);
                        }
                        return false;
                    }
                });

            } else {
                stemp_more.setRotation(-90);
                stemp_scan_interval.setText("");
                stemp_sensortype.setText("");
                CustomSlideAnimation a = new CustomSlideAnimation(stemp_layLayout,
                        CustomSlideAnimation.COLLAPSE);
                height = a.getHeight();
                stemp_layLayout.startAnimation(a);
            }
        }
    });
    // expand listener
    spressure_more.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (spressure_layLayout.getVisibility() != View.VISIBLE) {
                spressure_more.setRotation(90);
                CustomSlideAnimation a = new CustomSlideAnimation(spressure_layLayout,
                        CustomSlideAnimation.EXPAND);
                a.setHeight(height);
                spressure_layLayout.startAnimation(a);
                spressure_scan_interval = (EditText) rootView.findViewById(R.id.spressure_sensor_scan_interval);
                if (SPRESSURESensorScanCharacteristic != null) {
                    spressure_scan_interval.setText(SPRESSURESensorScanCharacteristic);
                }
                spressure_sensortype = (TextView) rootView.findViewById(R.id.spressure_sensor_type);
                if (SPRESSURESensorTypeCharacteristic != null) {
                    spressure_sensortype.setText(SPRESSURESensorTypeCharacteristic);
                }
                spressure_scan_interval.setOnEditorActionListener(new OnEditorActionListener() {

                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            int myNum = 0;

                            try {
                                myNum = Integer.parseInt(stemp_scan_interval.getText().toString());
                            } catch (NumberFormatException nfe) {
                                nfe.printStackTrace();
                            }
                            byte[] convertedBytes = convertingTobyteArray(Integer.toString(myNum));
                            BluetoothLeService.writeCharacteristicNoresponse(
                                    mReadSPRESSURESensorScanCharacteristic, convertedBytes);
                        }
                        return false;
                    }
                });
                Spinner spinner_filterconfiguration = (Spinner) rootView
                        .findViewById(R.id.spressure_filter_configuration);
                // Create an ArrayAdapter using the string array and a
                // default
                // spinner layout
                ArrayAdapter<CharSequence> adapter_filterconfiguration = ArrayAdapter.createFromResource(
                        getActivity(), R.array.filter_configuration_alert_array,
                        android.R.layout.simple_spinner_item);
                // Specify the layout to use when the list of choices
                // appears
                adapter_filterconfiguration
                        .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                // Apply the adapter to the spinner
                spinner_filterconfiguration.setAdapter(adapter_filterconfiguration);
                spressure_threshold_value = (EditText) rootView.findViewById(R.id.spressure_threshold);
                spressure_threshold_value.setOnEditorActionListener(new OnEditorActionListener() {

                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            int myNum = 0;

                            try {
                                myNum = Integer.parseInt(spressure_threshold_value.getText().toString());
                            } catch (NumberFormatException nfe) {
                                nfe.printStackTrace();
                            }
                            byte[] convertedBytes = convertingTobyteArray(Integer.toString(myNum));
                            BluetoothLeService.writeCharacteristicNoresponse(
                                    mReadSPRESSUREThresholdCharacteristic, convertedBytes);
                        }
                        return false;
                    }
                });

            } else {
                spressure_more.setRotation(-90);
                spressure_scan_interval.setText("");
                spressure_sensortype.setText("");
                spressure_threshold_value.setText("");
                CustomSlideAnimation a = new CustomSlideAnimation(spressure_layLayout,
                        CustomSlideAnimation.COLLAPSE);
                height = a.getHeight();
                spressure_layLayout.startAnimation(a);
            }

        }
    });
    ImageButton acc_graph = (ImageButton) rootView.findViewById(R.id.acc_graph);
    setupAccChart(rootView);

    acc_graph.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mACCGraphLayoutParent.getVisibility() != View.VISIBLE) {
                mACCGraphLayoutParent.setVisibility(View.VISIBLE);

            } else {
                mACCGraphLayoutParent.setVisibility(View.GONE);
            }

        }
    });
    ImageButton stemp_graph = (ImageButton) rootView.findViewById(R.id.temp_graph);
    setupTempGraph(rootView);
    stemp_graph.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mTemperatureGraphLayoutParent.getVisibility() != View.VISIBLE) {
                mTemperatureGraphLayoutParent.setVisibility(View.VISIBLE);
            } else {
                mTemperatureGraphLayoutParent.setVisibility(View.GONE);
            }

        }
    });
    ImageButton spressure_graph = (ImageButton) rootView.findViewById(R.id.pressure_graph);
    setupPressureGraph(rootView);

    spressure_graph.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (mPressureGraphLayoutParent.getVisibility() != View.VISIBLE) {
                mPressureGraphLayoutParent.setVisibility(View.VISIBLE);

            } else {

                mPressureGraphLayoutParent.setVisibility(View.GONE);
            }

        }
    });
    setHasOptionsMenu(true);
    return rootView;
}

From source file:com.stanleyidesis.quotograph.ui.activity.LWQSettingsActivity.java

void setupSettings() {
    final String[] refreshPreferenceOptions = getResources().getStringArray(R.array.refresh_preference_options);
    ArrayAdapter<String> refreshOptionsAdapter = new ArrayAdapter<>(this, R.layout.spinner_item,
            refreshPreferenceOptions);// w w w. j  av a  2 s . c  o  m
    refreshOptionsAdapter.setDropDownViewResource(R.layout.spinner_drop_down_item);
    Spinner refreshSpinner = findById(settingsContainer, R.id.spinner_lwq_settings_refresh);
    refreshSpinner.setAdapter(refreshOptionsAdapter);
    refreshSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int index, long l) {
            // Log refresh rate choice
            LWQLoggerHelper.get().logRefreshRate((String) adapterView.getAdapter().getItem(index));
            final int[] refreshValues = getResources().getIntArray(R.array.refresh_preference_values);
            LWQPreferences.setRefreshPreference(refreshValues[index]);
            LWQAlarmController.resetAlarm();
        }

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

    // Blur
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        findById(settingsContainer, R.id.sb_lwq_settings_blur).setVisibility(View.GONE);
    } else {
        SeekBar blurBar = findById(settingsContainer, R.id.sb_lwq_settings_blur);
        blurBar.setProgress(LWQPreferences.getBlurPreference());
        blurBar.setOnSeekBarChangeListener(this);
    }

    // Dim
    SeekBar dimBar = findById(settingsContainer, R.id.sb_lwq_settings_dim);
    dimBar.setProgress(LWQPreferences.getDimPreference());
    dimBar.setOnSeekBarChangeListener(this);

    AppCompatCheckBox doubleTapCheckbox = findById(this, R.id.check_lwq_settings_double_tap);
    doubleTapCheckbox.setChecked(LWQPreferences.isDoubleTapEnabled());

    // Fonts
    findById(settingsContainer, R.id.btn_lwq_settings_fonts).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            chooseFontsDialog = new MaterialDialog.Builder(LWQSettingsActivity.this).title("Choose Fonts")
                    .adapter(new FontMultiselectAdapter(LWQSettingsActivity.this), LWQSettingsActivity.this)
                    .alwaysCallMultiChoiceCallback().autoDismiss(false).canceledOnTouchOutside(true)
                    .cancelListener(LWQSettingsActivity.this).build();
            chooseFontsDialog.show();
            // Log view
            AnalyticsUtils.trackScreenView(AnalyticsUtils.SCREEN_FONTS);
        }
    });

    // Images
    findById(settingsContainer, R.id.btn_lwq_settings_images).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            changeState(stateChooseImageSources);
            // Log view
            AnalyticsUtils.trackScreenView(AnalyticsUtils.SCREEN_IMAGES);
        }
    });
}

From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java

private void setModelSpinner(final Series series) {
    ArrayAdapter<String> adapter;

    if (series == null) {
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                Helper.getEmptyStringList());
    } else {//w  ww. java2 s. c o  m
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                series.getModelNames());
    }

    modelSpinner.setAdapter(adapter);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // ???
    if (series != null && series.getModelNames().size() == 2) {
        modelSpinner.setSelection(1);
    } else {
        modelSpinner.setSelection(lastModelIndex);
    }

    lastModelIndex = 0;
}

From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java

private void setBrandSpinner(final Country country) {
    ArrayAdapter<String> adapter;
    if (country == null) {
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                Helper.getEmptyStringList());
    } else {/* ww w.  j a v a  2  s.co m*/
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                country.getBrandNames());
    }

    brandSpinner.setAdapter(adapter);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // ?Spinner Adapter
    brandSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (country == null || i == 0) {
                setManufacturerSpinner(null);
            } else if (i >= 1) {
                setManufacturerSpinner(country.brands.get(i - 1));
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    // ???
    if (country != null && country.getBrandNames().size() == 2) {
        brandSpinner.setSelection(1);
    } else {
        brandSpinner.setSelection(lastBrandIndex);
    }

    lastBrandIndex = 0;
}

From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java

private void setCountrySpinner(final VehicleModel vehicleModel) {
    ArrayAdapter<String> adapter;

    if (vehicleModel == null) {
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                Helper.getEmptyStringList());
    } else {// ww  w .  j a va 2s .  c  o  m
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                vehicleModel.getCountryNames());
    }

    countrySpinner.setAdapter(adapter);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // ?Spinner Adapter
    countrySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (i == 0) {
                setBrandSpinner(null);
            } else if (i >= 1) {
                setBrandSpinner(vehicleModel.countries.get(i - 1));
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    countrySpinner.setSelection(lastCountryIndex);
    lastCountryIndex = 0;
}

From source file:com.df.dfcarchecker.CarCheck.CarCheckBasicInfoFragment.java

private void setManufacturerSpinner(final Brand brand) {
    ArrayAdapter<String> adapter;

    if (brand == null) {
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                Helper.getEmptyStringList());
    } else {/*from  w w w. j a  v  a2 s  .  c  om*/
        adapter = new ArrayAdapter<String>(rootView.getContext(), android.R.layout.simple_spinner_item,
                brand.getManufacturerNames());
    }

    manufacturerSpinner.setAdapter(adapter);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    // Spinner Adapter
    manufacturerSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (brand == null || i == 0) {
                setSeriesSpinner(null);
            } else if (i >= 1) {
                setSeriesSpinner(brand.manufacturers.get(i - 1));
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

    // ???
    if (brand != null && brand.getManufacturerNames().size() == 2) {
        manufacturerSpinner.setSelection(1);
    } else {
        manufacturerSpinner.setSelection(lastManufacturerIndex);
    }

    lastManufacturerIndex = 0;
}