Example usage for android.widget Spinner setAdapter

List of usage examples for android.widget Spinner setAdapter

Introduction

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

Prototype

@Override
public void setAdapter(SpinnerAdapter adapter) 

Source Link

Document

Sets the SpinnerAdapter used to provide the data which backs this Spinner.

Usage

From source file:com.sakisds.icymonitor.activities.AddNotificationActivity.java

private void setAdapter(Spinner spinner, Sensor[] source) {
    String[] items = new String[source.length];
    for (int i = 0; i < items.length; i++) {
        items[i] = source[i].getName();//from w  ww . j ava2s.  c  om
    }

    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, items);
    spinner.setAdapter(adapter);
}

From source file:ca.farrelltonsolar.classic.DayLogChart.java

private void setupSpinner(MenuItem item) {
    try {//from w w  w .j  ava  2  s.  co  m
        item.setVisible(true);
        item.setActionView(R.layout.action_chart_select);
        View view = MenuItemCompat.getActionView(item);
        if (view instanceof Spinner) {
            Spinner spinner = (Spinner) view;
            String[] itemArray = getResources().getStringArray(R.array.day_log_chart_selection);
            ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this.getActivity(),
                    android.R.layout.simple_spinner_item, itemArray); //selected item will look like a spinner set from XML
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(spinnerArrayAdapter);
            spinner.setSelection(MonitorApplication.chargeControllers().getCurrentChargeController()
                    .getDayLogMenuSelection(), false);
            spinner.setOnItemSelectedListener(
                    new OnItemSelectedListenerWrapper(new AdapterView.OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            chartView.clearSeries();
                            if (position < mSeries.size()) {
                                MonitorApplication.chargeControllers().getCurrentChargeController()
                                        .setDayLogMenuSelection(position);
                                chartView.addSeries(mSeries.get(position));
                            }
                        }

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

                        }
                    }));
        }
    } catch (Exception ex) {
        Log.w(getClass().getName(), String.format("Day Log Chart failed to load setupSpinner %s ex: %s",
                Thread.currentThread().getName(), ex));
    }
}

From source file:hku.fyp14017.blencode.content.bricks.BroadcastBrick.java

@Override
public View getView(final Context context, int brickId, BaseAdapter baseAdapter) {
    if (animationState) {
        return view;
    }//w w w  . j a va  2  s. c  o  m
    if (view == null) {
        alphaValue = 255;
    }
    view = View.inflate(context, hku.fyp14017.blencode.R.layout.brick_broadcast, null);
    view = getViewWithAlpha(alphaValue);
    setCheckboxView(hku.fyp14017.blencode.R.id.brick_broadcast_checkbox);

    checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            checked = isChecked;
            adapter.handleCheck(BroadcastBrick.this, isChecked);
        }
    });

    final Spinner broadcastSpinner = (Spinner) view
            .findViewById(hku.fyp14017.blencode.R.id.brick_broadcast_spinner);
    broadcastSpinner.setFocusableInTouchMode(false);
    broadcastSpinner.setFocusable(false);
    if (!(checkbox.getVisibility() == View.VISIBLE)) {
        broadcastSpinner.setClickable(true);
        broadcastSpinner.setEnabled(true);
    } else {
        broadcastSpinner.setClickable(false);
        broadcastSpinner.setEnabled(false);
    }

    broadcastSpinner.setAdapter(MessageContainer.getMessageAdapter(context));
    broadcastSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selectedMessage = broadcastSpinner.getSelectedItem().toString();
            if (selectedMessage
                    .equals(context.getString(hku.fyp14017.blencode.R.string.new_broadcast_message))) {
                showNewMessageDialog(broadcastSpinner);
            } else {
                broadcastMessage = selectedMessage;
                adapterView = parent;
            }
        }

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

    setSpinnerSelection(broadcastSpinner);
    return view;
}

From source file:org.eyeseetea.malariacare.LoginActivity.java

private void initDataDownloadPeriodDropdown() {
    if (!BuildConfig.loginDataDownloadPeriod) {
        return;/*from  www .  j  a  v  a  2  s .c o m*/
    }

    ViewGroup loginViewsContainer = (ViewGroup) findViewById(R.id.login_dynamic_views_container);

    getLayoutInflater().inflate(R.layout.login_spinner, loginViewsContainer, true);

    //Add left text for the spinner "title"
    findViewById(R.id.date_spinner_container).setVisibility(View.VISIBLE);
    TextView textView = (TextView) findViewById(R.id.data_text_view);
    textView.setText(R.string.download);

    //add options
    ArrayList<String> dataLimitOptions = new ArrayList<>();
    dataLimitOptions.add(getString(R.string.no_data));
    dataLimitOptions.add(getString(R.string.last_6_days));
    dataLimitOptions.add(getString(R.string.last_6_weeks));
    dataLimitOptions.add(getString(R.string.last_6_months));

    final ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(this,
            android.R.layout.simple_spinner_item, dataLimitOptions);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    //add spinner
    Spinner spinner = (Spinner) findViewById(R.id.data_spinner);
    spinner.setVisibility(View.VISIBLE);
    spinner.setAdapter(spinnerArrayAdapter);

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            PreferencesState.getInstance().setDataLimitedByDate(spinnerArrayAdapter.getItem(pos).toString());
        }

        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
    //select the selected option or default no data option
    String dateLimit = PreferencesState.getInstance().getDataLimitedByDate();
    if (dateLimit.equals("")) {
        spinner.setSelection(spinnerArrayAdapter.getPosition(getString(R.string.no_data)));
    } else {
        spinner.setSelection(spinnerArrayAdapter.getPosition(dateLimit));
    }
}

From source file:org.gnucash.android.ui.chart.PieChartActivity.java

/**
 * Sets up settings and data for the account type spinner. Currently used only {@code EXPENSE} and {@code INCOME}
 * account types.//from   ww w. j av  a2s .c om
 */
private void setUpSpinner() {
    Spinner spinner = (Spinner) findViewById(R.id.chart_data_spinner);
    ArrayAdapter<AccountType> dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,
            Arrays.asList(AccountType.EXPENSE, AccountType.INCOME));
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(dataAdapter);
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            mAccountType = (AccountType) ((Spinner) findViewById(R.id.chart_data_spinner)).getSelectedItem();
            mEarliestTransactionDate = new LocalDateTime(
                    mTransactionsDbAdapter.getTimestampOfEarliestTransaction(mAccountType, mCurrencyCode));
            mLatestTransactionDate = new LocalDateTime(
                    mTransactionsDbAdapter.getTimestampOfLatestTransaction(mAccountType, mCurrencyCode));
            mChartDate = mLatestTransactionDate;
            setData(false);
        }

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

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    thisview = inflater.inflate(R.layout.settings, container, false);

    SharedPreferences sharedPref = getActivity().getSharedPreferences("uart_settings", Context.MODE_PRIVATE);

    UartSettings defaults = new UartSettings();

    Spinner spinner1 = (Spinner) thisview.findViewById(R.id.spinnerBaud);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(getActivity(), R.array.baud_array,
            R.layout.spinner_item_settings);
    // Specify the layout to use when the list of choices appears
    adapter1.setDropDownViewResource(R.layout.spinner_item_settings);
    // Apply the adapter to the spinner
    spinner1.setAdapter(adapter1);
    SetSpinnerSelection(sharedPref, spinner1, "baudrate", defaults.baudrate);

    Spinner spinner2 = (Spinner) thisview.findViewById(R.id.spinnerBits);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(), R.array.databits_array,
            R.layout.spinner_item_settings);
    // Specify the layout to use when the list of choices appears
    adapter2.setDropDownViewResource(R.layout.spinner_item_settings);
    // Apply the adapter to the spinner
    spinner2.setAdapter(adapter2);//w w  w. j  a va  2s  . com
    SetSpinnerSelection(sharedPref, spinner2, "databits", defaults.dataBits);

    Spinner spinner3 = (Spinner) thisview.findViewById(R.id.spinnerParity);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter3 = ArrayAdapter.createFromResource(getActivity(), R.array.parity_array,
            R.layout.spinner_item_settings);
    // Specify the layout to use when the list of choices appears
    adapter3.setDropDownViewResource(R.layout.spinner_item_settings);
    // Apply the adapter to the spinner
    spinner3.setAdapter(adapter3);
    spinner3.setSelection(sharedPref.getInt("parity", defaults.parity));

    Spinner spinner4 = (Spinner) thisview.findViewById(R.id.spinnerStopbits);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter4 = ArrayAdapter.createFromResource(getActivity(), R.array.stopbits_array,
            R.layout.spinner_item_settings);
    // Specify the layout to use when the list of choices appears
    adapter4.setDropDownViewResource(R.layout.spinner_item_settings);
    // Apply the adapter to the spinner
    spinner4.setAdapter(adapter4);
    SetSpinnerSelection(sharedPref, spinner4, "stopbits", defaults.stopBits);

    Spinner spinner5 = (Spinner) thisview.findViewById(R.id.spinnerFlow);
    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter<CharSequence> adapter5 = ArrayAdapter.createFromResource(getActivity(), R.array.flowcontrol,
            R.layout.spinner_item_settings);
    // Specify the layout to use when the list of choices appears
    adapter5.setDropDownViewResource(R.layout.spinner_item_settings);
    // Apply the adapter to the spinner
    spinner5.setAdapter(adapter5);
    spinner5.setSelection(sharedPref.getInt("flowcontrol", defaults.flowControl));

    String[] devList;
    try {
        devList = usb.createDeviceList();
        usbDevicesFound = devList.length;
    } catch (D2xxManager.D2xxException e) {
        devList = new String[1];
        devList[0] = e.getLocalizedMessage();
    }

    if (devList.length == 0) {
        devList = new String[1];
        devList[0] = getString(R.string.error_noAdapter);
    }

    Spinner spinner6 = (Spinner) thisview.findViewById(R.id.spinnerInterfce);

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(activity,
            R.layout.spinner_item_settings, devList);
    spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item_settings);
    spinner6.setAdapter(spinnerArrayAdapter);

    Button button1 = (Button) thisview.findViewById(R.id.button1);
    button1.setEnabled(usbDevicesFound > 0);

    button1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            doConnect();
        }
    });

    if (usbDevicesFound == 0)
        spinner6.setBackgroundColor(Color.MAGENTA);
    else
        spinner6.setBackgroundColor(Color.TRANSPARENT);

    return thisview;
}

From source file:com.redwoodsystems.android.apps.LightingListFragment.java

private void setupLocationSpinner() {
    Log.d(TAG, "setupLocationSpinner called");
    //TODO:/*from  w  w w.  ja va  2s.co  m*/
    //Setup lastLocationId if present and user hasn't selected a new location(?)
    Spinner spinner = (Spinner) getActivity().findViewById(R.id.locationSpinner);
    model = mLocationDbHelper.fetchAllLocations();
    mContext.startManagingCursor(model);
    mSpinnerAdapter = new LocationSpinnerAdapter(model);
    spinner.setAdapter(mSpinnerAdapter);

    OnItemSelectedListener spinnerListener = new spinnerOnItemSelectedListener(mContext, mSpinnerAdapter);
    spinner.setOnItemSelectedListener(spinnerListener);

    //special case:
    //if there are no locations in the spinner, then setupScenesList will not be called
    //hence, clear the mCurrentLocation and scenesAdapter to avoid displaying old scene values
    if (model.getCount() == 0) {
        mCurrentLocation = null;
        if (mSceneAdapter != null) {
            Log.d(TAG, "clearing mSceneAdapter");
            mSceneAdapter.clear();
            mActiveSceneName = null;
        }

        //raise a toast
        Toast.makeText(getActivity(), "Update Settings and add Locations to use this application",
                Toast.LENGTH_SHORT).show();
    }
}

From source file:com.example.amit.tellymoviebuzzz.ImdbFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // The CursorAdapter will take data from our cursor and populate the ListView.
    mForecastAdapter = new ImdbAdapter(getActivity(), null, 0);

    View rootView = inflater.inflate(R.layout.imdbthisyear_main, container, false);

    // Get a reference to the ListView, and attach this adapter to it.
    ListView listView1 = (ListView) rootView.findViewById(R.id.listview_imdbthisyear_movies);
    listView1.setAdapter(mForecastAdapter);

    final String[] str = { "Action", "Adventure", "Animation", "Comedy", "Crime", "Documentary", "Drama",
            "Family", "Fantasy", "Foreign", "History", "Horror", "Music", "Mystery", "Romance",
            "Science Fiction", "TV Movie", "Thriller", "War", "Western", "Others" };

    Spinner sp1 = (Spinner) rootView.findViewById(R.id.spinnerthisyear);
    //final Spinner sp2= (Spinner) findViewById(R.id.spinner2);

    ArrayAdapter<String> adp1 = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,
            str);//from   w ww .  j a  v  a  2 s .co  m
    adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp1.setAdapter(adp1);

    sp1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) {
            // TODO Auto-generated method stub
            // Toast.makeText(getBaseContext(),list.get(position), Toast.LENGTH_SHORT).show();

            String val = str[position];

            Bundle bund = new Bundle();
            bund.putString("choice", val);
            // bund.
            getLoaderManager().restartLoader(FORECAST_LOADER, bund, ImdbFragment.this);

        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }

    });

    // Spinner spinner = (Spinner) rootView.findViewById(R.id.spinnerthisyear);

    /// String[] options = {"India","USA","UK"};

    // android.R.layout.support_simple_spinner_dropdown_item

    // We'll call our MainActivity
    listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            // CursorAdapter returns a cursor at the correct position for getItem(), or null
            // if it cannot seek to that position.
            Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
            if (cursor != null) {
                // String locationSetting = Utility.getPreferredLocation(getActivity());
                String movieSetting = "thisyear";
                //Utility.getPreferredMovie(getActivity());

                // Intent intent = new Intent(getActivity(), DetailActivity.class)
                //        .setData(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
                //               locationSetting, cursor.getLong(COL_WEATHER_DATE)
                //       ));
                // Intent intent = new Intent(getActivity(), DetailActivity.class)
                //         .setData(MovieContract.MovieNumberEntry.buildMovieTypeWithMovieId(movieSetting, cursor.getString(COL_MOVIE_SETTING)));

                Intent intent = new Intent(getActivity(), DetailActivity.class);
                // .setData(cursor.getString(ImdbFragment.COL_TMDBID));
                intent.putExtra("movieid", cursor.getString(ImdbFragment.COL_TMDBID));

                startActivity(intent);
            }
        }
    });
    return rootView;
}

From source file:edu.rosehulman.grocerydroid.ItemDialogFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_dialog_item, container, false);

    // EditText nameBox = (EditText) view.findViewById(R.id.item_name_box);
    AutoCompleteTextView nameBox = (AutoCompleteTextView) view.findViewById(R.id.item_name_box);

    nameBox.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);

    //      String[] names = new String[] { "Bob", "Joe", "Caleb", "Jonathan",
    //            "Elise" };

    String[] foodNames = getResources().getStringArray(R.array.food_names);

    //      ArrayAdapter<String> autoAdapter = new ArrayAdapter<String>(
    //            getActivity(), android.R.layout.simple_list_item_1, names);
    ArrayAdapter<String> autoAdapter = new ArrayAdapter<String>(getActivity(), R.layout.dropdown_item,
            foodNames);/*from   w ww. j  av a  2 s  .  c  om*/

    // android.R.layout.sherlock.* both white/invisible
    // android.R.layout.
    // simple_spinner_item too thin
    // simple list item 2: crash
    // activity_list_item crash
    //simple_spinner_dropdown_item

    nameBox.setAdapter(autoAdapter);

    // mEditIcon.setOnKeyListener(new OnKeyListener() {
    // @Override
    // public boolean onKey(View v, int keyCode, KeyEvent event) {
    // // If the event is a key-down event on the "enter" button
    // if ((event.getAction() == KeyEvent.ACTION_DOWN)
    // && (keyCode == KeyEvent.KEYCODE_ENTER)) {
    // Toast.makeText(StockActivity.this, tv.getText(),
    // Toast.LENGTH_SHORT).show();
    // return true;
    // }
    // return false;
    // }
    // });

    EditText priceBox = (EditText) view.findViewById(R.id.item_price_box);
    priceBox.setInputType(InputType.TYPE_CLASS_PHONE);
    // priceBox.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL);

    // first true : is signed, second one : is decimal
    priceBox.setKeyListener(new DigitsKeyListener(false, true));

    EditText sizeBox = (EditText) view.findViewById(R.id.item_unit_size_box);
    sizeBox.setText("" + mItem.getUnitSize());

    Spinner unitSpinner = (Spinner) view.findViewById(R.id.item_unit_label_spinner);
    ArrayAdapter<Item.UnitLabel> adapter;
    adapter = new ArrayAdapter<Item.UnitLabel>(this.getActivity(), android.R.layout.simple_spinner_item,
            Item.UnitLabel.values());
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    unitSpinner.setAdapter(adapter);

    EditText numStockBox = (EditText) view.findViewById(R.id.item_num_stock);
    numStockBox.setText("" + mItem.getNStock());

    // If this activity was started with the purpose of editing an existing
    // item, then we use the item passed in the intent to populate the
    // spinners and edit text boxes.
    if (!mItem.getName().equals("")) {
        // TODO Make non-focusable, non-touchable so it doesn't kick off the drop down.
        // But it doesn't work!
        nameBox.setFocusable(false);
        nameBox.setFocusableInTouchMode(false);
        nameBox.setText(mItem.getName());
        // Reset the focus & touch
        nameBox.setFocusable(true);
        nameBox.setFocusableInTouchMode(true);

        priceBox.setText(Float.toString(mItem.getPrice()));

        unitSpinner.setSelection(mItem.getUnitLabel().ordinal());
    }

    Button incrementNumStockButton = (Button) view.findViewById(R.id.item_increment_num_stock);
    incrementNumStockButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText et = (EditText) view.findViewById(R.id.item_num_stock);
            int numStock = getIntegerFromEditText(et);
            numStock++;
            et.setText(numStock + "");
        }
    });

    Button decrementNumStockButton = (Button) view.findViewById(R.id.item_decrement_num_stock);
    decrementNumStockButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText et = (EditText) view.findViewById(R.id.item_num_stock);
            int numStock = getIntegerFromEditText(et);
            numStock--;
            et.setText(numStock + "");
        }
    });

    Button saveButton = (Button) view.findViewById(R.id.item_save_button);
    saveButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            EditText et = (EditText) view.findViewById(R.id.item_name_box);
            String name = et.getText().toString();

            et = (EditText) view.findViewById(R.id.item_price_box);
            float price = getFloatFromEditText(et);

            et = (EditText) view.findViewById(R.id.item_unit_size_box);
            float size = getFloatFromEditText(et);

            Spinner spinner = (Spinner) view.findViewById(R.id.item_unit_label_spinner);
            int unitIndex = spinner.getSelectedItemPosition();

            et = (EditText) view.findViewById(R.id.item_num_stock);
            int numStock = getIntegerFromEditText(et);

            mItem = new Item(mItem.getId(), mItem.getListId(), name, numStock, mItem.getNBuy(), price, size,
                    Item.UnitLabel.values()[unitIndex], mItem.isBought(), mItem.getStockIdx(),
                    mItem.getShopIdx());
            if (mMode == Mode.ADD) {
                ((ShoppingListActivity) getActivity()).addItem(mItem);
            } else if (mMode == Mode.EDIT) {
                ((ShoppingListActivity) getActivity()).updateItem(mItem);
            } else {
                // shouldn't get here.
            }
            dismiss();
        }
    });

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

    Button deleteButton = (Button) view.findViewById(R.id.item_delete_button);
    deleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mMode == Mode.EDIT) {
                ConfirmDeleteItemDialogFragment df = new ConfirmDeleteItemDialogFragment();
                df.setItem(mItem);
                df.show(getActivity().getSupportFragmentManager(), "confirm");
            }
            // Otherwise, we are adding this item, so we don't need to
            // delete it.
            // TODO: Remove modes altogether once autocomplete works, since
            // every item here will exist and be beging added.
            // CONSIDER: at that point, I will need to make sure that items
            // that have a name only (from autocomplete) have been saved in
            // the DB
            // and have a unique ID so they can be deleted.
            dismiss();
        }
    });

    return view;
}

From source file:org.thaliproject.nativetest.app.fragments.SettingsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_settings, container, false);

    mSettings = Settings.getInstance(view.getContext());
    mSettings.load();/*from w  ww  .  ja  va  2s  .  co m*/

    mConnectionTimeoutEditText = (EditText) view.findViewById(R.id.connectionTimeoutEditText);
    mConnectionTimeoutEditText.setText(String.valueOf(mSettings.getConnectionTimeout()));
    mConnectionTimeoutEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() > 0) {
                try {
                    mSettings.setConnectionTimeout(Long.parseLong(editable.toString()));
                } catch (NumberFormatException e) {
                    Log.e(TAG, e.getMessage(), e);
                    mConnectionTimeoutEditText.setText(String.valueOf(mSettings.getConnectionTimeout()));
                }
            }
        }
    });

    mPortNumberEditText = (EditText) view.findViewById(R.id.portNumberEditText);
    mPortNumberEditText.setText(String.valueOf(mSettings.getPortNumber()));
    mPortNumberEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() > 0 && !editable.toString().equals("-")) {
                try {
                    mSettings.setPortNumber(Integer.parseInt(editable.toString()));
                } catch (NumberFormatException e) {
                    Log.e(TAG, e.getMessage(), e);
                    mPortNumberEditText.setText(String.valueOf(mSettings.getPortNumber()));
                }
            }
        }
    });

    mListenForIncomingConnectionsCheckbox = (CheckBox) view
            .findViewById(R.id.listenForIncomingConnectionCheckbox);
    mListenForIncomingConnectionsCheckbox.setChecked(mSettings.getListenForIncomingConnections());
    mListenForIncomingConnectionsCheckbox
            .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    mSettings.setListenForIncomingConnections(b);
                }
            });

    mHandshakeRequiredCheckbox = (CheckBox) view.findViewById(R.id.handshakeRequiredCheckBox);
    mHandshakeRequiredCheckbox.setChecked(mSettings.getHandshakeRequired());
    mHandshakeRequiredCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            mSettings.setHandshakeRequired(b);
        }
    });

    mEnableWifiCheckBox = (CheckBox) view.findViewById(R.id.enableWifiCheckBox);
    mEnableWifiCheckBox.setChecked(mSettings.getEnableWifiDiscovery());
    mEnableWifiCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            mSettings.setEnableWifiDiscovery(b);
        }
    });

    mEnableBleCheckBox = (CheckBox) view.findViewById(R.id.enableBleCheckBox);
    mEnableBleCheckBox.setChecked(mSettings.getEnableBleDiscovery());
    mEnableBleCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            mSettings.setEnableBleDiscovery(b);
        }
    });

    Spinner spinner = (Spinner) view.findViewById(R.id.advertiseModeSpinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(view.getContext(),
            R.array.advertise_mode_string_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setSelection(mSettings.getAdvertiseMode());
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int index, long l) {
            mSettings.setAdvertiseMode(index);
        }

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

    spinner = (Spinner) view.findViewById(R.id.advertiseTxPowerLevelSpinner);
    adapter = ArrayAdapter.createFromResource(view.getContext(), R.array.advertise_tx_power_level_string_array,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setSelection(mSettings.getAdvertiseTxPowerLevel());
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int index, long l) {
            mSettings.setAdvertiseTxPowerLevel(index);
        }

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

    spinner = (Spinner) view.findViewById(R.id.scanModeSpinner);
    adapter = ArrayAdapter.createFromResource(view.getContext(), R.array.scan_mode_string_array,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setSelection(mSettings.getScanMode());
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int index, long l) {
            mSettings.setScanMode(index);
        }

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

    mBufferSizeEditText = (EditText) view.findViewById(R.id.bufferSizeEditText);
    mBufferSizeEditText.setText(String.valueOf(mSettings.getBufferSize()));
    mBufferSizeEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() > 0) {
                try {
                    mSettings.setBufferSize(Integer.parseInt(editable.toString()));
                } catch (NumberFormatException e) {
                    Log.e(TAG, e.getMessage(), e);
                    mBufferSizeEditText.setText(String.valueOf(mSettings.getBufferSize()));
                }
            }
        }
    });

    mDataAmountEditText = (EditText) view.findViewById(R.id.dataAmountEditText);
    mDataAmountEditText.setText(String.valueOf(mSettings.getDataAmount()));
    mDataAmountEditText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (editable.length() > 0) {
                try {
                    mSettings.setDataAmount(Long.parseLong(editable.toString()));
                } catch (NumberFormatException e) {
                    Log.e(TAG, e.getMessage(), e);
                    mDataAmountEditText.setText(String.valueOf(mSettings.getDataAmount()));
                }
            }
        }
    });

    mEnableAutoConnectCheckBox = (CheckBox) view.findViewById(R.id.autoConnectCheckBox);
    mEnableAutoConnectCheckBox.setChecked(mSettings.getAutoConnect());
    mEnableAutoConnectCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            mSettings.setAutoConnect(b);
        }
    });

    mEnableAutoConnectEvenWhenIncomingConnectionEstablishedCheckBox = (CheckBox) view
            .findViewById(R.id.autoConnectEvenWhenIncomingCheckBox);
    mEnableAutoConnectEvenWhenIncomingConnectionEstablishedCheckBox
            .setChecked(mSettings.getAutoConnectEvenWhenIncomingConnectionEstablished());
    mEnableAutoConnectEvenWhenIncomingConnectionEstablishedCheckBox
            .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                    mSettings.setAutoConnectEvenWhenIncomingConnectionEstablished(b);
                }
            });

    return view;
}