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.ichi2.anki.multimediacard.activity.TranslationActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        boolean b = savedInstanceState.getBoolean(BUNDLE_KEY_SHUT_OFF, false);
        if (b) {//from   w w w  .  ja v  a2 s .c  om
            finishCancel();
            return;
        }
    }

    setContentView(R.layout.activity_translation);

    try {
        mSource = getIntent().getExtras().getString(EXTRA_SOURCE).toString();
    } catch (Exception e) {
        mSource = "";
    }

    // If translation fails this is a default - source will be returned.
    mTranslation = mSource;

    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.MainLayoutInTranslationActivity);

    TextView tv = new TextView(this);
    tv.setText(getText(R.string.multimedia_editor_trans_poweredglosbe));
    linearLayout.addView(tv);

    TextView tvFrom = new TextView(this);
    tvFrom.setText(getText(R.string.multimedia_editor_trans_from));
    linearLayout.addView(tvFrom);

    mLanguageLister = new LanguagesListerGlosbe(this);

    mSpinnerFrom = new Spinner(this);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            mLanguageLister.getLanguages());
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mSpinnerFrom.setAdapter(adapter);
    linearLayout.addView(mSpinnerFrom);

    TextView tvTo = new TextView(this);
    tvTo.setText(getText(R.string.multimedia_editor_trans_to));
    linearLayout.addView(tvTo);

    mSpinnerTo = new Spinner(this);
    ArrayAdapter<String> adapterTo = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
            mLanguageLister.getLanguages());
    adapterTo.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mSpinnerTo.setAdapter(adapterTo);
    linearLayout.addView(mSpinnerTo);

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

    // Try to set spinner value to last selected position
    String fromLang = preferences.getString("translatorLastLanguageFrom", "");
    String toLang = preferences.getString("translatorLastLanguageTo", "");
    mSpinnerFrom.setSelection(getSpinnerIndex(mSpinnerFrom, fromLang));
    mSpinnerTo.setSelection(getSpinnerIndex(mSpinnerTo, toLang));
    // Setup button
    Button btnDone = new Button(this);
    btnDone.setText(getText(R.string.multimedia_editor_trans_translate));
    btnDone.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // Remember currently selected language
            String fromLang = mSpinnerFrom.getSelectedItem().toString();
            String toLang = mSpinnerTo.getSelectedItem().toString();
            preferences.edit().putString("translatorLastLanguageFrom", fromLang).commit();
            preferences.edit().putString("translatorLastLanguageTo", toLang).commit();
            // Get translation
            translate();
        }
    });

    linearLayout.addView(btnDone);

}

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);/*w  w w .ja v a2s  .com*/

    // 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.ueu.uninet.it.IragarkiaBidali.java

/**
 * Prestatu iragarki berria bidaltzeko formularioa
 *//*from ww w . jav  a 2s .  com*/
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.iragarkia_bidali);

    this.ekintza = this;
    this.izena = (EditText) findViewById(R.id.editTextIzena);
    this.izenburua = (EditText) findViewById(R.id.editTextIzenburua);
    this.eposta = (EditText) findViewById(R.id.editTextEposta);
    this.telefonoa = (EditText) findViewById(R.id.editTextTelefonoa);
    this.mezua = (EditText) findViewById(R.id.editTextDeskribapena);
    this.ohar_legala = (CheckBox) findViewById(R.id.checkBoxlegalAdviceBidali);
    this.errobota = (EditText) findViewById(R.id.editTextErrobota);

    this.atala = (Spinner) findViewById(R.id.spinnerAtala);
    imgView = (ImageView) findViewById(R.id.ImageView);
    upload = (Button) findViewById(R.id.Upload);
    bidali = (Button) findViewById(R.id.iragarkiaBidali);

    // Iragarkiak irudirik badu galeriatik kargatu
    upload.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "Aukeratu irudi bat.", Toast.LENGTH_SHORT).show();
            try {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Irudia aukeratu"), PICK_IMAGE);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
    });

    // Formularioa bidali
    bidali.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            if (balidatu()) {
                dialog = ProgressDialog.show(IragarkiaBidali.this, "Fitxategia igotzen eta mezua bidaltzen",
                        "Itxaron mesedez...", true);
                //Formularioa eta irudia bidali
                new ImageUploadTask().execute();
            }

        }
    });

    ArrayAdapter<String> iragarki_motak = new ArrayAdapter<String>(this, R.layout.spinner_view,
            getResources().getStringArray(R.array.iragarki_kategoriak));
    iragarki_motak.setDropDownViewResource(R.layout.spinner_view_dropdown);
    this.atala.setAdapter(iragarki_motak);

    // Sareko monitora prestatu
    NetworkConnectivity.sharedNetworkConnectivity().configure(this);
    NetworkConnectivity.sharedNetworkConnectivity().addNetworkMonitorListener(this);
    NetworkConnectivity.sharedNetworkConnectivity().startNetworkMonitor();

}

From source file:com.adithya321.sharesanalysis.fragments.PurchaseShareFragment.java

@Nullable
@Override//from  ww  w  .  j av  a2  s  . co  m
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_share_purchase, container, false);

    databaseHandler = new DatabaseHandler(getContext());
    sharePurchasesRecyclerView = (RecyclerView) root.findViewById(R.id.share_purchases_recycler_view);
    emptyTV = (TextView) root.findViewById(R.id.empty);
    arrow = (ImageView) root.findViewById(R.id.arrow);
    setRecyclerViewAdapter();

    FloatingActionButton addPurchaseFab = (FloatingActionButton) root.findViewById(R.id.add_purchase_fab);
    addPurchaseFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Dialog dialog = new Dialog(getContext());
            dialog.setTitle("Add Share Purchase");
            dialog.setContentView(R.layout.dialog_add_share_purchase);
            dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.WRAP_CONTENT);
            dialog.show();

            final AutoCompleteTextView name = (AutoCompleteTextView) dialog.findViewById(R.id.share_name);
            List<String> nseList = ShareUtils.getNseList(getContext());
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getContext(),
                    android.R.layout.simple_dropdown_item_1line, nseList);
            name.setAdapter(arrayAdapter);

            final Spinner spinner = (Spinner) dialog.findViewById(R.id.existing_spinner);
            ArrayList<String> shares = new ArrayList<>();
            for (Share share : sharesList) {
                shares.add(share.getName());
            }
            ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getContext(),
                    android.R.layout.simple_spinner_item, shares);
            spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(spinnerAdapter);

            final RadioButton newRB = (RadioButton) dialog.findViewById(R.id.radioBtn_new);
            RadioButton existingRB = (RadioButton) dialog.findViewById(R.id.radioBtn_existing);
            if (shares.size() == 0)
                existingRB.setVisibility(View.GONE);
            (newRB).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    name.setVisibility(View.VISIBLE);
                    spinner.setVisibility(View.GONE);
                }
            });

            (existingRB).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    name.setVisibility(View.GONE);
                    spinner.setVisibility(View.VISIBLE);
                }
            });

            Calendar calendar = Calendar.getInstance();
            year_start = calendar.get(Calendar.YEAR);
            month_start = calendar.get(Calendar.MONTH) + 1;
            day_start = calendar.get(Calendar.DAY_OF_MONTH);
            final Button selectDate = (Button) dialog.findViewById(R.id.select_date);
            selectDate.setText(new StringBuilder().append(day_start).append("/").append(month_start).append("/")
                    .append(year_start));
            selectDate.setOnClickListener(this);

            Button addPurchaseBtn = (Button) dialog.findViewById(R.id.add_purchase_btn);
            addPurchaseBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Share share = new Share();
                    share.setId(databaseHandler.getNextKey("share"));
                    share.setPurchases(new RealmList<Purchase>());
                    Purchase purchase = new Purchase();
                    purchase.setId(databaseHandler.getNextKey("purchase"));

                    if (newRB.isChecked()) {
                        String sName = name.getText().toString().trim();
                        if (sName.equals("")) {
                            Toast.makeText(getActivity(), "Invalid Name", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            share.setName(sName);
                            purchase.setName(sName);
                        }
                    }

                    String stringStartDate = year_start + " " + month_start + " " + day_start;
                    DateFormat format = new SimpleDateFormat("yyyy MM dd", Locale.ENGLISH);
                    try {
                        Date date = format.parse(stringStartDate);
                        share.setDateOfInitialPurchase(date);
                        purchase.setDate(date);
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), "Invalid Date", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    EditText quantity = (EditText) dialog.findViewById(R.id.no_of_shares);
                    try {
                        purchase.setQuantity(Integer.parseInt(quantity.getText().toString()));
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), "Invalid Number of Shares", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    EditText price = (EditText) dialog.findViewById(R.id.buying_price);
                    try {
                        purchase.setPrice(Double.parseDouble(price.getText().toString()));
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), "Invalid Buying Price", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    purchase.setType("buy");
                    if (newRB.isChecked()) {
                        if (!databaseHandler.addShare(share, purchase)) {
                            Toast.makeText(getActivity(), "Share Already Exists", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } else {
                        purchase.setName(spinner.getSelectedItem().toString());
                        databaseHandler.addPurchase(spinner.getSelectedItem().toString(), purchase);
                    }
                    setRecyclerViewAdapter();
                    dialog.dismiss();
                }
            });
        }
    });

    return root;
}

From source file:com.mifos.mifosxdroid.online.GenerateCollectionSheetFragment.java

public void inflateGroupSpinner(final int centerId) {

    API.centerService.getAllGroupsForCenter(centerId, new Callback<CenterWithAssociations>() {
        @Override/* w w w  .ja  va  2s  .co  m*/
        public void success(CenterWithAssociations centerWithAssociations, Response response) {

            List<Group> groups = centerWithAssociations.getGroupMembers();

            List<String> groupNames = new ArrayList<String>();

            groupNames.add(getString(R.string.spinner_group));
            groupNameIdHashMap.put(getString(R.string.spinner_group), -1);

            for (Group group : groups) {
                groupNames.add(group.getName());
                groupNameIdHashMap.put(group.getName(), group.getId());
            }

            ArrayAdapter<String> groupAdapter = new ArrayAdapter<String>(getActivity(),
                    android.R.layout.simple_spinner_item, groupNames);

            groupAdapter.notifyDataSetChanged();

            groupAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            sp_groups.setAdapter(groupAdapter);

        }

        @Override
        public void failure(RetrofitError retrofitError) {

        }
    });

}

From source file:com.wizard.ui.SimpleSpinnerChoiceFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_page_spinner, container, false);
    ((TextView) rootView.findViewById(android.R.id.title)).setText(mPage.getTitle());

    //for future use domain name
    // ((TextView) rootView.findViewById(R.id.ddomain)).setText(Integer.toString(mPage.getmNumberDomainQuestion()));

    final List<String> severitylist = new ArrayList<String>();
    /*/*w w w  .  j a  v a  2 s .  c  o  m*/
    severitylist.add("0 = None");
    severitylist.add("1 = Mild:symptoms present but causes little distress or disturbance");
    severitylist.add("2 = Moderate: some distress or disturbance to patient");
    severitylist.add("3 = Severe: major sourcwe of distress or disturbance to patient");
    */

    //set only numbers
    severitylist.add("0 = None");
    severitylist.add("1 = Mild");
    severitylist.add("2 = Moderate");
    severitylist.add("3 = Severe");

    spinnerSeverity = (Spinner) rootView.findViewById(R.id.spinnerSeverity);

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(),
            //  android.R.layout.simple_spinner_item, severitylist);
            //dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            R.layout.myspinner, severitylist);
    dataAdapter.setDropDownViewResource(R.layout.myspinner);

    spinnerSeverity.setAdapter(dataAdapter);

    spinnerSeverity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            int index = adapterView.getSelectedItemPosition();

            mPage.getData().putString("Severity", Integer.toString(index));
            mPage.notifyDataChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            int index = adapterView.getSelectedItemPosition();

            mPage.getData().putString("Severity", Integer.toString(index));
            mPage.notifyDataChanged();
        }
    });

    final List<String> frequencylist = new ArrayList<String>();

    /*
    frequencylist.add("1 = Rarely(<1/wk)");
    frequencylist.add("2 = Often(1/wk)");
    frequencylist.add("3 = Frequent(several times per week)");
    frequencylist.add("4 = Very Frequent(daily or all the time)");
    */

    //set only numbers
    frequencylist.add("1 = Rarely(<1/wk)");
    frequencylist.add("2 = Often(1/wk)");
    frequencylist.add("3 = Frequent(several times per week)");
    frequencylist.add("4 = Very Frequent(daily or all the time)");

    spinnerFrequency = (Spinner) rootView.findViewById(R.id.spinnerFrequency);

    ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this.getActivity(),
            // android.R.layout.simple_spinner_dropdown_item, frequencylist);
            //dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            R.layout.myspinner, frequencylist);
    dataAdapter2.setDropDownViewResource(R.layout.myspinner);
    spinnerFrequency.setAdapter(dataAdapter2);

    spinnerFrequency.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            int index = adapterView.getSelectedItemPosition();

            mPage.getData().putString("Frequency", Integer.toString(index));
            mPage.notifyDataChanged();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            int index = adapterView.getSelectedItemPosition();

            mPage.getData().putString("Frequency", Integer.toString(index));
            mPage.notifyDataChanged();
        }
    });

    // Pre-select currently selected items.

    new Handler().post(new Runnable() {
        @Override
        public void run() {
            ArrayList<String> selectedItems = mPage.getData().getStringArrayList(Page.SIMPLE_DATA_KEY);
            if (selectedItems == null || selectedItems.size() == 0) {
                return;
            }

            Set<String> selectedSet = new HashSet<String>(selectedItems);

            for (int i = 0; i < mChoices.size(); i++) {
                if (selectedSet.contains(mChoices.get(i))) {
                    //false spinnerSeverity.setItemChecked(i, true);

                }
            }
        }
    });

    return rootView;
}

From source file:mx.itdurango.rober.siitdocentes.ActivityAlumnos.java

/**
 * Permite descomponer el cdigo html que se enva con una estructura especifica para llenar los datos de la vista
 *
 * @param html cdigo html que se recibi de una peticin HttpGet, debe tener una estructura similar a la siguiente para que el proceso funcione correctamente
 *             <p/>/* w ww  .  j  a  va 2 s. c om*/
 *             <input name="periodo" type="hidden" value="20141" />
 *             <input name="materia" type="hidden" value="SD2424" />
 *             <input name="grupo" type="hidden" value="5VR" />
 *             <input name="docente" type="hidden" value="LOQR841213822" />
 *             <input name="fecha_captura" type="hidden" value="2014/06/12" />
 *             <table>
 *             <tr>
 *             <td>No</td>
 *             <td>Noctrl</td>
 *             <td>Nombre</td>
 *             <td>Unidad 1</td>
 *             <td>Unidad 1</td>
 *             <td>Unidad 3</td>
 *             <td>...</td>
 *             <td>Unidad N</td>
 *             </tr>
 *             <tr>
 *             <td>1</td>
 *             <td>9999999</td>
 *             <td>XXXXXXXXXXXXXXXXXXXXX</td>
 *             <td><input type="text" name="calif[1][1]" value="999"/></td>
 *             <td><input type="text" name="calif[1][2]" value="999"/></td>
 *             <td><input type="text" name="calif[1][3]" value="999"/></td>
 *             <td>...</td>
 *             <td><input type="text" name="calif[1][N]" value="999"/></td>
 *             </tr>
 *             <tr>
 *             <td>2</td>
 *             <td>888888888</td>
 *             <td>YYYYYYYYYYYYYYYYYYYYY</td>
 *             <td><input type="text" name="calif[2][1]" value="999"/></td>
 *             <td><input type="text" name="calif[2][2]" value="999"/></td>
 *             <td><input type="text" name="calif[2][3]" value="999"/></td>
 *             <td>...</td>
 *             <td><input type="text" name="calif[2][N]" value="999"/></td>
 *             </tr>
 *             <tr>
 *             <td>M</td>
 *             <td>000000000</td>
 *             <td>ZZZZZZZZZZZZZZZZZZZZZZ</td>
 *             <td><input type="text" name="calif[M][1]" value="999"/></td>
 *             <td><input type="text" name="calif[M][2]" value="999"/></td>
 *             <td><input type="text" name="calif[M][3]" value="999"/></td>
 *             <td>...</td>
 *             <td><input type="text" name="calif[M][N]" value="999"/></td>
 *             </tr>
 *             </table>
 */
void llenaAlumnos(String html) {
    //Generar un archivo de documento para almacenar los datos del html de forma que se pueda
    //manipular facilmente usando la librera Jsoup
    Document doc = Jsoup.parse(html);

    try {
        //extraer los valores de los elementos del formulario y almacenarlos en los atributos correspondientes de la clase
        Elements e = doc.getElementsByAttributeValue("name", "periodo");
        periodo = e.get(0).attr("value");
        e = doc.getElementsByAttributeValue("name", "materia");
        materia = e.get(0).attr("value");
        e = doc.getElementsByAttributeValue("name", "grupo");
        grupo = e.get(0).attr("value");
        e = doc.getElementsByAttributeValue("name", "docente");
        docente = e.get(0).attr("value");
        e = doc.getElementsByAttributeValue("name", "fecha_captura");
        fecha_captura = e.get(0).attr("value");

        //extraer la tabla correspondiente al listado de alumnos en el caso del siit.itdurango.edu.mx,
        // corresponde a la tabla numero 2 y ya que la numeracin comienza en 0, la tabla que necesitamos est en el indice 1
        Element tabla = doc.getElementsByTag("table").get(1);
        //Extraer todos los elementos de tipo tr que pertenecen a la tabla y almacenarlos en una coleccion de tipo Elements.
        Elements renglones = tabla.getElementsByTag("tr");
        //Recorrer la coleccin de renglones y almacenar cada uno en un objeto
        for (Element tr : renglones) {
            //para cada objeto tr, extraer sus elementos td y almacenarlos en una coleccion
            Elements tds = tr.getElementsByTag("td");
            //permite llevar el control de la columna que se est leyendo, ya que las columnas no tienen un id o clase, se realiza el proceso a mano.
            int col = 1;
            //contenedor de tipo AlumosParciales para almacenar la informacin de cada alumno (tr)
            AlumnosParciales c = new AlumnosParciales();
            for (Element td : tds) {
                if (col == 1) {// la columna 1 corresponde al nmero consecutivo de la tabla
                    c.setNum(td.html());
                } else if (col == 2) {// la columna 2 corresponde al nmero de control del alumno
                    c.setControl(td.html());
                } else if (col == 3) {// la columna 3 corresponde al nombre del alumno
                    c.setNombre(Estaticos.sanitize(td.html()));
                } else { //el resto de las columnas pertenecen a las calificaciones parciales
                    //se extrae el elemento <input> de la columna y se obtiene el atributo valor para recuperar la calificacin en caso de que ya hubiera sido asignada
                    String cal = td.getElementsByTag("input").get(0).attr("value");

                    ArrayList<String> calif = c.getCalificaciones();
                    calif.add(cal);
                    //se agrega la nueva calificacin al conjunto de calificaciones del alumno
                    c.setCalificaciones(calif);
                }
                col++; //incrementa el numero de columa
            }
            if (c.getCalificaciones().size() > 0) { //para evitar agregar al listado de alumnos el encabezado de la tabla, validamos que existan calificaciones.
                gcs.add(c);
            }
        }

        //Llenamos el spinner de unidades a partir del numero de calificaciones que existen en el arreglo
        List<String> spinnerArray = new ArrayList<String>();
        for (int i = 1; i <= gcs.get(1).getCalificaciones().size() - 1; i++) {
            spinnerArray.add("Unidad " + i);
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
                spinnerArray);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spn_unidad.setAdapter(adapter);

        //llenamos el listado de alumnos con la informacin que se obtuvo del proceso anterior
        alumnosParcialesAdapter = new AlumnosParcialesAdapter(this, gcs, unidad);
        lvAlumnos.setAdapter(alumnosParcialesAdapter);

    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(this, getString(R.string.error_parser), Toast.LENGTH_SHORT).show();
        finish(); //finaliza el intent actual para desplegar el anterior
    }
}

From source file:com.androguide.honamicontrol.kernel.cpucontrol.CPUFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root, Bundle savedInstanceState) {
    setHasOptionsMenu(true);/*w  ww.java  2s.  co m*/

    fa = (ActionBarActivity) super.getActivity();
    mActivity = getActivity();
    view = inflater.inflate(R.layout.card_cpu_control, root, false);

    preferences = PreferenceManager.getDefaultSharedPreferences(mActivity);

    graph = (LineGraph) view.findViewById(R.id.graph);
    line = new Line();
    LinePoint point = new LinePoint();
    point.setX(currX);
    point.setY(1);
    line.addPoint(point);
    line.setColor(Color.parseColor("#FFBB33"));
    graph.addLine(line);
    graph.setLineToFill(0);

    availableFrequencies = new String[0];
    String availableFrequenciesLine = CPUHelper.readOneLine(STEPS);
    if (availableFrequenciesLine != null) {
        availableFrequencies = availableFrequenciesLine.split(" ");
        Arrays.sort(availableFrequencies, new Comparator<String>() {
            @Override
            public int compare(String object1, String object2) {
                return Integer.valueOf(object1).compareTo(Integer.valueOf(object2));
            }
        });
    }

    int frequenciesNum = availableFrequencies.length - 1;

    String currentGovernor = CPUHelper.readOneLine(GOVERNOR);
    //        String currentIo = CPUHelper.getIOScheduler();
    String curMaxSpeed = CPUHelper.readOneLine(MAX_FREQ);
    String curMinSpeed = CPUHelper.readOneLine(MIN_FREQ);

    if (mIsTegra3) {
        String curTegraMaxSpeed = CPUHelper.readOneLine(TEGRA_MAX_FREQ);
        int curTegraMax = 0;
        try {
            curTegraMax = Integer.parseInt(curTegraMaxSpeed);
            if (curTegraMax > 0) {
                curMaxSpeed = Integer.toString(curTegraMax);
            }
        } catch (NumberFormatException ex) {
            curTegraMax = 0;
        }
    }

    String numOfCpus = CPUHelper.readOneLine(NUM_OF_CPUS);
    String[] cpuCount = numOfCpus.split("-");
    if (cpuCount.length > 1) {
        try {
            int cpuStart = Integer.parseInt(cpuCount[0]);
            int cpuEnd = Integer.parseInt(cpuCount[1]);

            mNumOfCpu = cpuEnd - cpuStart + 1;

            if (mNumOfCpu < 0)
                mNumOfCpu = 1;
        } catch (NumberFormatException ex) {
            mNumOfCpu = 1;
        }
    }

    mCurFreq = (TextView) view.findViewById(R.id.currspeed);

    mMaxSlider = (SeekBar) view.findViewById(R.id.max_slider);
    mMaxSlider.setMax(frequenciesNum);
    mMaxSpeedText = (TextView) view.findViewById(R.id.max_speed_text);
    mMaxSpeedText.setText(toMHz(curMaxSpeed));
    mMaxSlider.setProgress(Arrays.asList(availableFrequencies).indexOf(curMaxSpeed));
    mMaxSlider.setOnSeekBarChangeListener(this);

    mMinSlider = (SeekBar) view.findViewById(R.id.min_slider);
    mMinSlider.setMax(frequenciesNum);
    mMinSpeedText = (TextView) view.findViewById(R.id.min_speed_text);
    mMinSpeedText.setText(toMHz(curMinSpeed));
    mMinSlider.setProgress(Arrays.asList(availableFrequencies).indexOf(curMinSpeed));
    mMinSlider.setOnSeekBarChangeListener(this);

    mGovernor = (Spinner) view.findViewById(R.id.governor);
    String[] availableGovernors = CPUHelper.readOneLine(GOVERNORS_LIST).split(" ");
    ArrayAdapter<CharSequence> governorAdapter = new ArrayAdapter<CharSequence>(mActivity,
            android.R.layout.simple_spinner_item);
    governorAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    for (int i = 0; i < availableGovernors.length; i++) {
        governorAdapter.add(availableGovernors[i]);
    }
    mGovernor.setAdapter(governorAdapter);
    mGovernor.setSelection(Arrays.asList(availableGovernors).indexOf(currentGovernor));
    mGovernor.setOnItemSelectedListener(new GovListener());

    //        mIo = (Spinner) view.findViewById(R.id.io);
    //        String[] availableIo = CPUHelper.getAvailableIOSchedulers();
    //        ArrayAdapter<CharSequence> ioAdapter = new ArrayAdapter<CharSequence>(
    //                mActivity, android.R.layout.simple_spinner_item);
    //        ioAdapter
    //                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    //        for (int i = 0; i < availableIo.length; i++) {
    //            ioAdapter.add(availableIo[i]);
    //        }
    //        mIo.setAdapter(ioAdapter);
    //        mIo.setSelection(Arrays.asList(availableIo).indexOf(currentIo));
    //        mIo.setOnItemSelectedListener(new IOListener());

    return view;
}

From source file:com.github.jvanhie.discogsscrobbler.ReleaseListActivity.java

@Override
public boolean onCreateOptionsMenu(final Menu menu) {
    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("enable_discogs", true)) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.discogs_list, menu);
        //configure search box
        final MenuItem search = menu.findItem(R.id.list_search);
        SearchView searchView = (SearchView) search.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override// ww  w  .  j  av a2  s .c  om
            public boolean onQueryTextSubmit(String s) {
                menu.findItem(R.id.list_search).collapseActionView();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                mReleaseList.filter(s);
                return false;
            }
        });
        searchView.setQueryHint("Filter your releases");
        final MenuItem filter = menu.findItem(R.id.list_filter);
        if (!mFolders) {
            mDiscogs.getFolders(new Discogs.DiscogsDataWaiter<List<Folder>>() {
                @Override
                public void onResult(boolean success, List<Folder> data) {
                    if (success && data != null) {
                        mFolders = true;
                        Spinner s = (Spinner) filter.getActionView(); // find the spinner
                        ArrayAdapter<Folder> mSpinnerAdapter = new ArrayAdapter<Folder>(
                                getSupportActionBar().getThemedContext(),
                                android.R.layout.simple_spinner_dropdown_item, data);
                        mSpinnerAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
                        s.setAdapter(mSpinnerAdapter); // set the adapter
                        s.setSelection(0, false);
                        s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                mDiscogs.setFolderId(((Folder) adapterView.getItemAtPosition(i)).folderid);
                                //reload list with id
                                mReleaseList.loadList();
                                filter.collapseActionView();
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {
                                //filter.collapseActionView();
                            }
                        });
                    }
                }
            });
        }

        //make sure only one actionview is expanded
        MenuItemCompat.setOnActionExpandListener(filter, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem menuItem) {
                //collapse search
                search.collapseActionView();
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem menuItem) {
                return true;
            }
        });
        MenuItemCompat.setOnActionExpandListener(search, new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem menuItem) {
                //collapse search
                filter.collapseActionView();
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem menuItem) {
                return true;
            }
        });

        //s.setSelection(mSearchType,false);

        if (mSelected > 0) {
            if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("enable_lastfm", true)) {
                inflater.inflate(R.menu.release_detail_scrobble, menu);
            }
        }
    }
    return true;
}

From source file:es.usc.citius.servando.calendula.activities.CalendarActivity.java

private void setupPatientSpinner() {
    String[] names = new String[pats.size() + 1];

    names[0] = "Todos";
    for (int i = 0; i < pats.size(); i++) {
        names[i + 1] = pats.get(i).name();
    }//from ww w  . ja v  a  2s. c o  m

    ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.toolbar_spinner_item, names);
    adapter.setDropDownViewResource(R.layout.toolbar_spinner_item);
    Spinner spinner = (Spinner) findViewById(R.id.toolbar_spinner);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            selectedPatientIdx = i;
            onPatientUpdate();
        }

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

        }
    });

}