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:se.frikod.payday.DailyBudgetFragment.java

public void editBudgetItem(final View v, final int currentIndex) {

    LayoutInflater inflater = activity.getLayoutInflater();
    final View dialogView = inflater.inflate(R.layout.daily_budget_edit_budget_item, null);

    AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
    builder.setTitle(getString(R.string.edit_budget_item_title));

    final BudgetItem budgetItem;
    final EditText titleView = (EditText) dialogView.findViewById(R.id.budget_item_title);
    final Spinner typeView = (Spinner) dialogView.findViewById(R.id.budget_item_type);
    final EditText amountView = (EditText) dialogView.findViewById(R.id.budget_item_amount);

    if (currentIndex == NEW_BUDGET_ITEM) {
        budgetItem = null;//from   ww w .j  ava2 s  .co m
        builder.setTitle(getString(R.string.add_budget_item_dialog_title));
        builder.setPositiveButton(R.string.add_budget_item, null);
    } else {
        builder.setTitle(getString(R.string.edit_budget_item_title));

        budgetItem = budget.budgetItems.get(currentIndex);

        String title = budgetItem.title;
        BigDecimal amount = budgetItem.amount;
        int type;
        if (amount.signum() < 0) {
            type = 0;
            amount = amount.negate();
        } else {
            type = 1;
        }

        titleView.setText(title);
        typeView.setSelection(type);
        amountView.setText(amount.toString());

        builder.setNeutralButton(getString(R.string.delete_budget_item_yes),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE);
                        vibrator.vibrate(100);
                        budget.budgetItems.remove(currentIndex);
                        budget.saveBudgetItems();
                        updateBudgetItems();
                        dialog.dismiss();
                    }

                });
        builder.setPositiveButton(R.string.update_budget_item, null);
    }

    builder.setNegativeButton(getString(R.string.delete_budget_item_no), new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    /* onClick listener for update needs to be setup like this to
       prevent closing dialog on error
     */

    final AlertDialog d = builder.create();
    d.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {
            Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
            assert b != null;
            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    BigDecimal amount;
                    try {
                        amount = new BigDecimal(amountView.getText().toString());
                        if (typeView.getSelectedItemId() == 0)
                            amount = amount.negate();
                    } catch (NumberFormatException e) {

                        Toast.makeText(activity.getApplicationContext(),
                                getString(R.string.new_budget_item_no_amount_specified), Toast.LENGTH_SHORT)
                                .show();

                        return;
                    }

                    String title = titleView.getText().toString();

                    if (budgetItem != null) {
                        budgetItem.amount = amount;
                        budgetItem.title = title;
                    } else {
                        budget.budgetItems.add(new BudgetItem(title, amount));
                    }

                    budget.saveBudgetItems();
                    updateBudgetItems();
                    d.dismiss();
                }
            });
        }
    });

    d.setView(dialogView);
    d.show();
}

From source file:org.svij.taskwarriorapp.activities.TaskAddActivity.java

public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme_Holo_Light_DarkActionBar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_task_add);

    final TextView tvDueDate = (TextView) findViewById(R.id.tvDueDate);
    tvDueDate.setOnClickListener(new View.OnClickListener() {

        @Override/* www.ja  va 2  s  .  c o m*/
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            CalendarDatePickerDialog calendarDatePickerDialog = CalendarDatePickerDialog.newInstance(
                    TaskAddActivity.this, Calendar.getInstance().get(Calendar.YEAR),
                    Calendar.getInstance().get(Calendar.MONTH),
                    Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
            calendarDatePickerDialog.show(fm, "fragment_date_picker");
        }
    });

    final TextView tvDueTime = (TextView) findViewById(R.id.tvDueTime);
    tvDueTime.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            FragmentManager fm = getSupportFragmentManager();
            RadialTimePickerDialog timePickerDialog = RadialTimePickerDialog.newInstance(TaskAddActivity.this,
                    Calendar.getInstance().get(Calendar.HOUR_OF_DAY),
                    Calendar.getInstance().get(Calendar.MINUTE),
                    android.text.format.DateFormat.is24HourFormat(TaskAddActivity.this));
            timePickerDialog.show(fm, "fragment_time_picker_name");
        }
    });

    tvDueDate.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (TextUtils.isEmpty(tvDueTime.getText().toString())) {
                timestamp = 0;
            } else {
                cal.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
                cal.set(Calendar.MONTH, Calendar.getInstance().get(Calendar.MONTH));
                cal.set(Calendar.DAY_OF_MONTH, Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
                timestamp = cal.getTimeInMillis();
            }
            tvDueDate.setText("");
            return true;
        }
    });

    tvDueTime.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (TextUtils.isEmpty(tvDueDate.getText().toString())) {
                timestamp = 0;
            } else {
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                timestamp = cal.getTimeInMillis();
            }
            tvDueTime.setText("");
            return true;
        }
    });

    TaskDatabase dataSource = new TaskDatabase(this);
    ArrayList<String> projects = dataSource.getProjects();
    projects.removeAll(Collections.singleton(null));
    final AutoCompleteTextView actvProject = (AutoCompleteTextView) findViewById(R.id.actvProject);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            projects.toArray(new String[projects.size()]));
    actvProject.setAdapter(adapter);
    actvProject.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            actvProject.showDropDown();
            return false;
        }
    });

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();

    if (extras != null) {
        taskID = extras.getString("taskID");

        if (taskID != null) {
            data = new TaskDatabase(this);
            Task task = data.getTask(UUID.fromString(taskID));

            TextView etTaskAdd = (TextView) findViewById(R.id.etTaskAdd);
            Spinner spPriority = (Spinner) findViewById(R.id.spPriority);

            etTaskAdd.setText(task.getDescription());
            if (task.getDue() != null && task.getDue().getTime() != 0) {

                tvDueDate.setText(DateFormat.getDateInstance(DateFormat.SHORT).format(task.getDue()));
                if (!DateFormat.getTimeInstance().format(task.getDue()).equals("00:00:00")) {
                    tvDueTime.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(task.getDue()));
                }

                cal.setTime(task.getDue());
                timestamp = cal.getTimeInMillis();

            }
            actvProject.setText(task.getProject());

            Log.i("PriorityID", ":" + task.getPriorityID());
            spPriority.setSelection(task.getPriorityID());

            if (task.getTags() != null) {
                TextView etTags = (TextView) findViewById(R.id.etTags);
                String tagString = "";

                for (String s : task.getTags()) {
                    tagString += s + " ";
                }
                etTags.setText(tagString.trim());
            }
        } else {
            String action = intent.getAction();
            if ((action.equalsIgnoreCase(Intent.ACTION_SEND)
                    || action.equalsIgnoreCase("com.google.android.gm.action.AUTO_SEND"))
                    && intent.hasExtra(Intent.EXTRA_TEXT)) {
                String s = intent.getStringExtra(Intent.EXTRA_TEXT);
                TextView etTaskAdd = (TextView) findViewById(R.id.etTaskAdd);
                etTaskAdd.setText(s);
                addingTaskFromOtherApp = true;
            }
        }
    }

}

From source file:com.andreadec.musicplayer.MainActivity.java

private void equalizerSettings() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.equalizer);
    View view = getLayoutInflater().inflate(R.layout.layout_equalizer, null);
    builder.setView(view);//from   w  w  w . j av  a2  s.c  o  m

    builder.setOnCancelListener(new OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            updateExtendedMenu();
        }
    });
    builder.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            updateExtendedMenu();
        }
    });

    CheckBox checkBoxEqualizerEnabled = (CheckBox) view.findViewById(R.id.checkBoxEqualizerEnabled);
    checkBoxEqualizerEnabled.setChecked(musicService.getEqualizerEnabled());
    checkBoxEqualizerEnabled.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            musicService.toggleEqualizer();
            updateExtendedMenu();
        }
    });

    String[] availablePresets = musicService.getEqualizerAvailablePresets();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            availablePresets);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Spinner spinnerEqualizerPreset = (Spinner) view.findViewById(R.id.spinnerEqualizerPreset);
    spinnerEqualizerPreset.setAdapter(adapter);
    spinnerEqualizerPreset.setSelection(musicService.getEqualizerPreset());

    spinnerEqualizerPreset.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            musicService.setEqualizerPreset(position);
        }

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

From source file:nya.miku.wishmaster.ui.settings.AutohideActivity.java

@SuppressLint("InflateParams")
@Override/* w w  w.  ja  va2 s  . c o  m*/
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    Object item = l.getItemAtPosition(position);
    final int changeId;
    if (item instanceof AutohideRule) {
        changeId = position - 1;
    } else {
        changeId = -1; //-1 - ?  
    }

    Context dialogContext = Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB
            ? new ContextThemeWrapper(this, R.style.Neutron_Medium)
            : this;
    View dialogView = LayoutInflater.from(dialogContext).inflate(R.layout.dialog_autohide_rule, null);
    final EditText regexEditText = (EditText) dialogView.findViewById(R.id.dialog_autohide_regex);
    final Spinner chanSpinner = (Spinner) dialogView.findViewById(R.id.dialog_autohide_chan_spinner);
    final EditText boardEditText = (EditText) dialogView.findViewById(R.id.dialog_autohide_boardname);
    final EditText threadEditText = (EditText) dialogView.findViewById(R.id.dialog_autohide_threadnum);
    final CheckBox inCommentCheckBox = (CheckBox) dialogView.findViewById(R.id.dialog_autohide_in_comment);
    final CheckBox inSubjectCheckBox = (CheckBox) dialogView.findViewById(R.id.dialog_autohide_in_subject);
    final CheckBox inNameCheckBox = (CheckBox) dialogView.findViewById(R.id.dialog_autohide_in_name);

    chanSpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, chans));
    if (changeId != -1) {
        AutohideRule rule = (AutohideRule) item;
        regexEditText.setText(rule.regex);
        int chanPosition = chans.indexOf(rule.chanName);
        chanSpinner.setSelection(chanPosition != -1 ? chanPosition : 0);
        boardEditText.setText(rule.boardName);
        threadEditText.setText(rule.threadNumber);
        inCommentCheckBox.setChecked(rule.inComment);
        inSubjectCheckBox.setChecked(rule.inSubject);
        inNameCheckBox.setChecked(rule.inName);
    } else {
        chanSpinner.setSelection(0);
    }

    DialogInterface.OnClickListener save = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String regex = regexEditText.getText().toString();
            if (regex.length() == 0) {
                Toast.makeText(AutohideActivity.this, R.string.autohide_error_empty_regex, Toast.LENGTH_LONG)
                        .show();
                return;
            }

            try {
                Pattern.compile(regex, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.DOTALL);
            } catch (Exception e) {
                CharSequence message = null;
                if (e instanceof PatternSyntaxException) {
                    String eMessage = e.getMessage();
                    if (!TextUtils.isEmpty(eMessage)) {
                        SpannableStringBuilder a = new SpannableStringBuilder(
                                getString(R.string.autohide_error_incorrect_regex));
                        a.append('\n');
                        int startlen = a.length();
                        a.append(eMessage);
                        a.setSpan(new TypefaceSpan("monospace"), startlen, a.length(),
                                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        message = a;
                    }
                }
                if (message == null)
                    message = getString(R.string.error_unknown);
                Toast.makeText(AutohideActivity.this, message, Toast.LENGTH_LONG).show();
                return;
            }

            AutohideRule rule = new AutohideRule();
            int spinnerSelectedPosition = chanSpinner.getSelectedItemPosition();
            rule.regex = regex;
            rule.chanName = spinnerSelectedPosition > 0 ? chans.get(spinnerSelectedPosition) : ""; // 0 ? = ? 
            rule.boardName = boardEditText.getText().toString();
            rule.threadNumber = threadEditText.getText().toString();
            rule.inComment = inCommentCheckBox.isChecked();
            rule.inSubject = inSubjectCheckBox.isChecked();
            rule.inName = inNameCheckBox.isChecked();

            if (!rule.inComment && !rule.inSubject && !rule.inName) {
                Toast.makeText(AutohideActivity.this, R.string.autohide_error_no_condition, Toast.LENGTH_LONG)
                        .show();
                return;
            }

            if (changeId == -1) {
                rulesJson.put(rule.toJson());
            } else {
                rulesJson.put(changeId, rule.toJson());
            }
            rulesChanged();
        }
    };
    AlertDialog dialog = new AlertDialog.Builder(this).setView(dialogView)
            .setTitle(changeId == -1 ? R.string.autohide_add_rule_title : R.string.autohide_edit_rule_title)
            .setPositiveButton(R.string.autohide_save_button, save)
            .setNegativeButton(android.R.string.cancel, null).create();
    dialog.setCanceledOnTouchOutside(false);
    dialog.show();
}

From source file:org.svij.taskwarriorapp.TaskAddActivity.java

public void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_task_add);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    final TextView tvDueDate = (TextView) findViewById(R.id.tvDueDate);
    tvDueDate.setOnClickListener(new View.OnClickListener() {

        @Override/*from   w ww. j av  a  2 s . c  o m*/
        public void onClick(View v) {
            DatePickerFragment date = new DatePickerFragment();
            date.setCallBack(onDate);
            date.setTimestamp(timestamp);
            date.show(getSupportFragmentManager().beginTransaction(), "date_dialog");
        }
    });

    final TextView tvDueTime = (TextView) findViewById(R.id.tvDueTime);
    tvDueTime.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            TimePickerFragment date = new TimePickerFragment();
            date.setCallBack(onTime);
            date.setTimestamp(timestamp);
            date.show(getSupportFragmentManager().beginTransaction(), "time_dialog");
        }
    });

    tvDueDate.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (TextUtils.isEmpty(tvDueTime.getText().toString())) {
                timestamp = 0;
            } else {
                cal.set(Calendar.YEAR, Calendar.getInstance().get(Calendar.YEAR));
                cal.set(Calendar.MONTH, Calendar.getInstance().get(Calendar.MONTH));
                cal.set(Calendar.DAY_OF_MONTH, Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
                timestamp = cal.getTimeInMillis();
            }
            tvDueDate.setText("");
            return true;
        }
    });

    tvDueTime.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (TextUtils.isEmpty(tvDueDate.getText().toString())) {
                timestamp = 0;
            } else {
                cal.set(Calendar.HOUR_OF_DAY, 0);
                cal.set(Calendar.MINUTE, 0);
                cal.set(Calendar.SECOND, 0);
                timestamp = cal.getTimeInMillis();
            }
            tvDueTime.setText("");
            return true;
        }
    });

    TaskDataSource dataSource = new TaskDataSource(this);
    ArrayList<String> projectsAR = dataSource.getProjects();
    projectsAR.removeAll(Collections.singleton(null));
    String[] projects = projectsAR.toArray(new String[projectsAR.size()]);
    final AutoCompleteTextView actvProject = (AutoCompleteTextView) findViewById(R.id.actvProject);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            projects);
    actvProject.setAdapter(adapter);

    actvProject.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View arg0, MotionEvent arg1) {
            actvProject.showDropDown();
            return false;
        }
    });

    Intent intent = getIntent();
    Bundle extras = intent.getExtras();

    if (extras != null) {
        taskID = extras.getString("taskID");

        if (taskID != null) {
            datasource = new TaskDataSource(this);
            Task task = datasource.getTask(UUID.fromString(taskID));

            TextView etTaskAdd = (TextView) findViewById(R.id.etTaskAdd);
            Spinner spPriority = (Spinner) findViewById(R.id.spPriority);
            TextView etTags = (TextView) findViewById(R.id.etTags);

            etTaskAdd.setText(task.getDescription());
            if (task.getDue() != null && task.getDue().getTime() != 0) {

                tvDueDate.setText(DateFormat.getDateInstance(DateFormat.SHORT).format(task.getDue()));
                if (!DateFormat.getTimeInstance().format(task.getDue()).equals("00:00:00")) {
                    tvDueTime.setText(DateFormat.getTimeInstance(DateFormat.SHORT).format(task.getDue()));
                }

                cal.setTime(task.getDue());
                timestamp = cal.getTimeInMillis();

            }
            actvProject.setText(task.getProject());
            Log.i("PriorityID", ":" + task.getPriorityID());
            spPriority.setSelection(task.getPriorityID());
            etTags.setText(task.getTags());
        } else {
            String action = intent.getAction();
            if ((action.equalsIgnoreCase(Intent.ACTION_SEND)
                    || action.equalsIgnoreCase("com.google.android.gm.action.AUTO_SEND"))
                    && intent.hasExtra(Intent.EXTRA_TEXT)) {
                String s = intent.getStringExtra(Intent.EXTRA_TEXT);
                TextView etTaskAdd = (TextView) findViewById(R.id.etTaskAdd);
                etTaskAdd.setText(s);
                addingTaskFromOtherApp = true;
            }
        }
    }

}

From source file:com.asksven.betterbatterystats.StatsActivity.java

/**
 * Take the change of selection from the spinners into account and refresh the ListView
 * with the right data//  w ww  .  jav a  2 s  .co m
 */
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    // this method is fired even if nothing has changed so we nee to find that out
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    boolean bChanged = false;

    // id is in the order of the spinners, 0 is stat, 1 is stat_type
    if (parent == (Spinner) findViewById(R.id.spinnerStatType)) {
        // detect if something changed
        String newStat = (String) ((ReferencesAdapter) parent.getAdapter()).getItemName(position);
        if ((m_refFromName != null) && (!m_refFromName.equals(newStat))) {
            if (LogSettings.DEBUG)
                Log.i(TAG, "Spinner from changed from " + m_refFromName + " to " + newStat);

            m_refFromName = newStat;
            bChanged = true;
            // we need to update the second spinner
            m_spinnerToAdapter.filterToSpinner(newStat, this);
            m_spinnerToAdapter.notifyDataSetChanged();

            // select the right element
            Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
            if (spinnerStatSampleEnd.isShown()) {
                spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(m_refToName));
            } else {
                spinnerStatSampleEnd
                        .setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
            }

        } else {
            return;
        }

    } else if (parent == (Spinner) findViewById(R.id.spinnerStatSampleEnd)) {
        String newStat = (String) ((ReferencesAdapter) parent.getAdapter()).getItemName(position);
        if ((m_refFromName != null) && (!m_refToName.equals(newStat))) {
            if (LogSettings.DEBUG)
                Log.i(TAG, "Spinner to changed from " + m_refToName + " to " + newStat);

            m_refToName = newStat;
            bChanged = true;
        } else {
            return;
        }

    } else if (parent == (Spinner) findViewById(R.id.spinnerStat)) {
        int iNewStat = position;
        if (m_iStat != iNewStat) {
            m_iStat = iNewStat;
            bChanged = true;
        } else {
            return;
        }
    } else {
        Log.e(TAG, "ProcessStatsActivity.onItemSelected error. ID could not be resolved");
        Toast.makeText(this, getString(R.string.info_unknown_state), Toast.LENGTH_SHORT).show();

    }

    Reference myReferenceFrom = ReferenceStore.getReferenceByName(m_refFromName, this);
    Reference myReferenceTo = ReferenceStore.getReferenceByName(m_refToName, this);

    TextView tvSince = (TextView) findViewById(R.id.TextViewSince);

    long sinceMs = StatsProvider.getInstance().getSince(myReferenceFrom, myReferenceTo);

    if (sinceMs != -1) {
        String sinceText = DateUtils.formatDuration(sinceMs);
        sinceText += " "
                + StatsProvider.getInstance().getBatteryLevelFromTo(myReferenceFrom, myReferenceTo, true);

        tvSince.setText(sinceText);
        if (LogSettings.DEBUG)
            Log.i(TAG, "Since " + sinceText);
    } else {
        tvSince.setText("n/a ");
        if (LogSettings.DEBUG)
            Log.i(TAG, "Since: n/a ");

    }
    // @todo fix this: this method is called twice
    //m_listViewAdapter.notifyDataSetChanged();
    if (bChanged) {
        // as the source changed fetch the data
        doRefresh(false);
    }
}

From source file:com.google.sample.beaconservice.ManageBeaconFragment.java

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

    advertisedId_Type = (TextView) rootView.findViewById(R.id.advertisedId_Type);
    advertisedId_Id = (TextView) rootView.findViewById(R.id.advertisedId_Id);
    status = (TextView) rootView.findViewById(R.id.status);
    placeId = (TextView) rootView.findViewById(R.id.placeId);
    placeId.setOnClickListener(new View.OnClickListener() {
        @Override// w ww.ja v a  2 s.  co  m
        public void onClick(View v) {
            editLatLngAction();
        }
    });
    latLng = (TextView) rootView.findViewById(R.id.latLng);
    latLng.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editLatLngAction();
        }
    });
    mapView = (ImageView) rootView.findViewById(R.id.mapView);
    mapView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editLatLngAction();
        }
    });

    expectedStability = (TextView) rootView.findViewById(R.id.expectedStability);
    expectedStability.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit Stability");
            final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                    R.array.stability_enums, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            final Spinner spinner = new Spinner(getActivity());
            spinner.setAdapter(adapter);
            // Set the position of the spinner to the current value.
            if (beacon.expectedStability != null
                    && !beacon.expectedStability.equals(Beacon.STABILITY_UNSPECIFIED)) {
                for (int i = 0; i < spinner.getCount(); i++) {
                    if (beacon.expectedStability.equals(spinner.getItemAtPosition(i))) {
                        spinner.setSelection(i);
                    }
                }
            }
            builder.setView(spinner);
            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    beacon.expectedStability = (String) spinner.getSelectedItem();
                    updateBeacon();
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
        }
    });

    description = (TextView) rootView.findViewById(R.id.description);
    description.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit description");
            final EditText editText = new EditText(getActivity());
            editText.setText(description.getText());
            builder.setView(editText);
            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    beacon.description = editText.getText().toString();
                    updateBeacon();
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
        }
    });

    actionButton = (Button) rootView.findViewById(R.id.actionButton);

    decommissionButton = (Button) rootView.findViewById(R.id.decommissionButton);
    decommissionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(getActivity()).setTitle("Decommission Beacon")
                    .setMessage("Are you sure you want to decommission this beacon? This operation is "
                            + "irreversible and the beacon cannot be registered again")
                    .setPositiveButton("Decommission", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Callback decommissionCallback = new Callback() {
                                @Override
                                public void onFailure(Request request, IOException e) {
                                    logErrorAndToast("Failed request: " + request, e);
                                }

                                @Override
                                public void onResponse(Response response) throws IOException {
                                    if (response.isSuccessful()) {
                                        beacon.status = Beacon.STATUS_DECOMMISSIONED;
                                        updateBeacon();
                                    } else {
                                        String body = response.body().string();
                                        logErrorAndToast("Unsuccessful decommissionBeacon request: " + body);
                                    }
                                }
                            };
                            client.decommissionBeacon(decommissionCallback, beacon.getBeaconName());
                        }
                    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
        }
    });

    attachmentsDivider = rootView.findViewById(R.id.attachmentsDivider);
    attachmentsLabel = (TextView) rootView.findViewById(R.id.attachmentsLabel);
    attachmentsTable = (TableLayout) rootView.findViewById(R.id.attachmentsTableLayout);

    // Fetch the namespace for the developer console project ID. We redraw the UI once that
    // request completes.
    // TODO: cache this.
    Callback listNamespacesCallback = new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            logErrorAndToast("Failed request: " + request, e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String body = response.body().string();
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(body);
                    JSONArray namespaces = json.getJSONArray("namespaces");
                    // At present there can be only one namespace.
                    String tmp = namespaces.getJSONObject(0).getString("namespaceName");
                    if (tmp.startsWith("namespaces/")) {
                        namespace = tmp.substring("namespaces/".length());
                    } else {
                        namespace = tmp;
                    }
                    redraw();
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException", e);
                }
            } else {
                logErrorAndToast("Unsuccessful listNamespaces request: " + body);
            }
        }
    };
    client.listNamespaces(listNamespacesCallback);
    return rootView;
}

From source file:org.alfresco.mobile.android.application.widgets.DocumentFolderPickerFragment.java

private void refreshSpinners() {
    // UPLOAD FOLDER
    Spinner spinner = (Spinner) rootView.findViewById(R.id.import_folder_spinner);
    UploadFolderAdapter upLoadadapter = null;
    if (getActivity() instanceof FolderShortcutActivity) {
        upLoadadapter = new UploadFolderAdapter(getActivity(), R.layout.row_single_line, FOLDER_SHORTCUT_LIST);
    } else {//from w  ww .ja  v  a2s  .c o  m
        upLoadadapter = new UploadFolderAdapter(getActivity(), R.layout.row_single_line, FOLDER_ACTIONS_LIST);
    }
    spinner.setAdapter(upLoadadapter);
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            rootFolderTypeId = (Integer) parent.getItemAtPosition(pos);
            rootFolderTypeIndex = pos;
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // DO Nothing
        }
    });
    if (rootFolderTypeId == null) {
        rootFolderTypeIndex = 0;
    }
    spinner.setSelection(rootFolderTypeIndex);

    // ACTIONS ASSOCIATED
    if (getActivity() instanceof FolderShortcutActivity) {
        rootView.findViewById(R.id.actions_spinner_title).setVisibility(View.GONE);
        rootView.findViewById(R.id.actions_spinner).setVisibility(View.GONE);
        return;
    }
    spinner = (Spinner) rootView.findViewById(R.id.actions_spinner);
    ActionShortcutAdapter actionAdapter = new ActionShortcutAdapter(getActivity(), R.layout.row_single_line,
            ACTIONS_LIST);
    spinner.setAdapter(actionAdapter);
    spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            actionId = (Integer) parent.getItemAtPosition(pos);
            actionIdIndex = pos;
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // DO Nothing
        }
    });
    if (actionId == null) {
        actionIdIndex = 0;
    }
    spinner.setSelection(actionIdIndex);

}

From source file:edu.cmu.hcii.hangg.beeksbeacon.Fragments.ManageBeaconFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Log.i(TAG, "bi.id: " + beaconInstance.id + ", bi.googleType: " + beaconInstance.googleType);
    View rootView = inflater.inflate(R.layout.fragment_manage_beacon, container, false);

    advertisedId_Type = (TextView) rootView.findViewById(R.id.advertisedId_Type);
    advertisedId_Id = (TextView) rootView.findViewById(R.id.advertisedId_Id);
    status = (TextView) rootView.findViewById(R.id.status);
    placeId = (TextView) rootView.findViewById(R.id.placeId);
    placeId.setOnClickListener(new View.OnClickListener() {
        @Override/*from   w ww .ja v  a  2  s  .c  o m*/
        public void onClick(View v) {
            editLatLngAction();
        }
    });
    latLng = (TextView) rootView.findViewById(R.id.latLng);
    latLng.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editLatLngAction();
        }
    });
    mapView = (ImageView) rootView.findViewById(R.id.mapView);
    mapView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            editLatLngAction();
        }
    });

    expectedStability = (TextView) rootView.findViewById(R.id.expectedStability);
    expectedStability.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit Stability");
            final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                    R.array.stability_enums, android.R.layout.simple_spinner_item);
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            final Spinner spinner = new Spinner(getActivity());
            spinner.setAdapter(adapter);
            // Set the position of the spinner to the current value.
            if (beaconInstance.expectedStability != null
                    && !beaconInstance.expectedStability.equals(BeaconInstance.STABILITY_UNSPECIFIED)) {
                for (int i = 0; i < spinner.getCount(); i++) {
                    if (beaconInstance.expectedStability.equals(spinner.getItemAtPosition(i))) {
                        spinner.setSelection(i);
                    }
                }
            }
            builder.setView(spinner);
            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    beaconInstance.expectedStability = (String) spinner.getSelectedItem();
                    updateBeacon();
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
        }
    });

    description = (TextView) rootView.findViewById(R.id.description);
    description.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setTitle("Edit description");
            final EditText editText = new EditText(getActivity());
            editText.setText(description.getText());
            builder.setView(editText);
            builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    beaconInstance.description = editText.getText().toString();
                    updateBeacon();
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
        }
    });

    actionButton = (Button) rootView.findViewById(R.id.actionButton);

    decommissionButton = (Button) rootView.findViewById(R.id.decommissionButton);
    decommissionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(getActivity()).setTitle("Decommission Beacon")
                    .setMessage("Are you sure you want to decommission this beacon? This operation is "
                            + "irreversible and the beacon cannot be registered again")
                    .setPositiveButton("Decommission", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Callback decommissionCallback = new Callback() {
                                @Override
                                public void onFailure(Request request, IOException e) {
                                    logErrorAndToast("Failed request: " + request, e);
                                }

                                @Override
                                public void onResponse(Response response) throws IOException {
                                    if (response.isSuccessful()) {
                                        beaconInstance.status = BeaconInstance.STATUS_DECOMMISSIONED;
                                        updateBeacon();
                                    } else {
                                        String body = response.body().string();
                                        logErrorAndToast("Unsuccessful decommissionBeacon request: " + body);
                                    }
                                }
                            };
                            client.decommissionBeacon(decommissionCallback, beaconInstance.getBeaconName());
                        }
                    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
        }
    });

    attachmentsDivider = rootView.findViewById(R.id.attachmentsDivider);
    attachmentsLabel = (TextView) rootView.findViewById(R.id.attachmentsLabel);
    attachmentsTable = (TableLayout) rootView.findViewById(R.id.attachmentsTableLayout);

    // Fetch the namespace for the developer console project ID. We redraw the UI once that
    // request completes.
    // TODO: cache this.
    Callback listNamespacesCallback = new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            logErrorAndToast("Failed request: " + request, e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String body = response.body().string();
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(body);
                    JSONArray namespaces = json.getJSONArray("namespaces");
                    // At present there can be only one namespace.
                    String tmp = namespaces.getJSONObject(0).getString("namespaceName");
                    if (tmp.startsWith("namespaces/")) {
                        namespace = tmp.substring("namespaces/".length());
                    } else {
                        namespace = tmp;
                    }
                    redraw();
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException", e);
                }
            } else {
                logErrorAndToast("Unsuccessful listNamespaces request: " + body);
            }
        }
    };
    client.listNamespaces(listNamespacesCallback);
    return rootView;
}

From source file:com.money.manager.ex.investment.watchlist.WatchlistFragment.java

/**
 * Select the current account in the accounts dropdown.
 *///from  w w  w  .j a v a 2s  .com
private void selectCurrentAccount() {
    Spinner spinner = getAccountsSpinner();
    if (spinner == null)
        return;

    // find account
    SimpleCursorAdapter adapter = (SimpleCursorAdapter) spinner.getAdapter();
    if (adapter == null)
        return;

    Cursor cursor = adapter.getCursor();
    int position = Constants.NOT_SET;

    for (int i = 0; i < adapter.getCount(); i++) {
        cursor.moveToPosition(i);
        String accountIdString = cursor.getString(cursor.getColumnIndex(Account.ACCOUNTID));
        int accountId = Integer.parseInt(accountIdString);
        if (accountId == getAccountId()) {
            position = i;
            break;
        }
    }

    spinner.setSelection(position);
}