Example usage for android.widget Spinner Spinner

List of usage examples for android.widget Spinner Spinner

Introduction

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

Prototype

public Spinner(Context context) 

Source Link

Document

Constructs a new spinner with the given context's theme.

Usage

From source file:Main.java

public static Spinner createSpinner(Context context) {
    //return new Spinner(context, 1);
    return new Spinner(context);

}

From source file:org.noorganization.shoppinglist.view.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    m_presenter = ShoppingListPresenter.getInstance(this);
    if (m_presenter.needsToCreateAList()) {
        m_presenter.createList("Test List");
    }/* w ww. ja va2  s.co  m*/

    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_shoppinglist);

    m_listSelector = new Spinner(this);
    m_listSelector.setAdapter(new ListSpinnerAdapter(m_presenter.getLists()));
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(m_listSelector);

    updateListDropDown();

    m_listSelector.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> _parent, View _view, int _position, long _selectedId) {
            m_presenter.selectList((int) _selectedId);
            // TODO refresh listfragments
        }

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

}

From source file:org.kaaproject.kaa.demo.iotworld.smarthome.fragment.device.AbstractGeoFencingDeviceFragment.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override//from   ww w . j a va2 s. c  o m
protected void setupView(LayoutInflater inflater, View rootView) {
    mGeoFencingStatusSpinner = new Spinner(mActivity);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        int color = ColorUtils
                .darkerColor(getResources().getColor(mDevice.getDeviceType().getBaseColorResId()));
        mGeoFencingStatusSpinner.getPopupBackground()
                .setColorFilter(new PorterDuffColorFilter(color, Mode.MULTIPLY));
    }
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(mActivity,
            R.layout.toolbar_spinner_item, getResources().getStringArray(R.array.geofencing_status));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        spinnerArrayAdapter.setDropDownViewResource(R.layout.toolbar_spinner_dropdown_item);
    } else {
        spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    }
    mGeoFencingStatusSpinner.setAdapter(spinnerArrayAdapter);

    updateGeoFencingSpinnerWidth();

    mGeoFencingStatusSpinner.setOnItemSelectedListener(this);
}

From source file:com.normalexception.app.rx8club.dialog.MoveThreadDialog.java

/**
 * Constructor for method that is used to move a thread from one
 * forum to another   //from  w  w w . j  ava 2  s  . c  om
 * @param ctx         The source context/activity   
 * @param securitytoken   The security token for the session
 * @param src_thread   The source thread
 * @param tTitle      The new thread title
 * @param options      The options from the move dialog
 */
public MoveThreadDialog(final Fragment ctx, final String securitytoken, final String src_thread, String tTitle,
        final Map<String, Integer> options) {
    builder = new AlertDialog.Builder(ctx.getActivity());

    // Set up the input
    final TextView lbl_title = new TextView(ctx.getActivity());
    final EditText title = new EditText(ctx.getActivity());
    final TextView lbl_dest = new TextView(ctx.getActivity());
    final Spinner destination = new Spinner(ctx.getActivity());

    // Lets make sure the user didn't accidentally click this
    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
            case DialogInterface.BUTTON_POSITIVE:
                newTitle = title.getText().toString();
                String selectText = destination.getSelectedItem().toString();
                selection = options.get(selectText);

                AsyncTask<Void, String, Void> updaterTask = new AsyncTask<Void, String, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        try {
                            HtmlFormUtils.adminMoveThread(securitytoken, src_thread, newTitle,
                                    Integer.toString(selection));
                        } catch (Exception e) {
                            Log.e(TAG, "Error Submitting Form For Move", e);
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        ctx.getFragmentManager().popBackStack();
                        CategoryFragment cFrag = (CategoryFragment) ((ThreadFragment) ctx).getParentCategory();
                        cFrag.refreshView();
                    }
                };
                updaterTask.execute();
                break;
            case DialogInterface.BUTTON_NEGATIVE:
                break;
            }
        }
    };

    // Specify the type of input expected
    lbl_title.setText("Thread Title");
    lbl_title.setTextColor(Color.WHITE);
    lbl_dest.setText("Desination");
    lbl_dest.setTextColor(Color.WHITE);
    title.setInputType(InputType.TYPE_CLASS_TEXT);
    title.setText(tTitle);

    List<String> values = new ArrayList<String>();
    values.addAll(options.keySet());

    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(ctx.getActivity(),
            android.R.layout.simple_spinner_item, values);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    destination.setAdapter(dataAdapter);

    LinearLayout ll = new LinearLayout(ctx.getActivity());
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.addView(lbl_title);
    ll.addView(title);
    ll.addView(lbl_dest);
    ll.addView(destination);

    builder.setView(ll);

    builder.setTitle(R.string.dialogMoveThread).setPositiveButton(R.string.Move, dialogClickListener)
            .setNegativeButton(R.string.cancel, dialogClickListener);
}

From source file:com.nextgis.maplibui.formcontrol.DoubleCombobox.java

@Override
public void init(JSONObject element, List<Field> fields, Bundle savedState, Cursor featureCursor,
        SharedPreferences preferences) throws JSONException {
    mSubCombobox = new Spinner(getContext());
    JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY);
    mFieldName = attributes.getString(JSON_FIELD_LEVEL1_KEY);
    mSubFieldName = attributes.getString(JSON_FIELD_LEVEL2_KEY);
    mIsShowLast = ControlHelper.isSaveLastValue(attributes);
    setEnabled(ControlHelper.isEnabled(fields, mFieldName));

    String lastValue = null;/*from www  .  j  a v a 2 s  . c o m*/
    String subLastValue = null;
    if (ControlHelper.hasKey(savedState, mFieldName) && ControlHelper.hasKey(savedState, mSubFieldName)) {
        lastValue = savedState.getString(ControlHelper.getSavedStateKey(mFieldName));
        subLastValue = savedState.getString(ControlHelper.getSavedStateKey(mSubFieldName));
    } else if (null != featureCursor) {
        int column = featureCursor.getColumnIndex(mFieldName);
        int subColumn = featureCursor.getColumnIndex(mSubFieldName);
        if (column >= 0)
            lastValue = featureCursor.getString(column);
        if (subColumn >= 0)
            subLastValue = featureCursor.getString(subColumn);
    } else if (mIsShowLast) {
        lastValue = preferences.getString(mFieldName, null);
        subLastValue = preferences.getString(mSubFieldName, null);
    }

    JSONArray values = attributes.optJSONArray(JSON_VALUES_KEY);
    int defaultPosition = 0;
    int lastValuePosition = -1;
    int subLastValuePosition = -1;
    mAliasValueMap = new HashMap<>();
    mSubAliasValueMaps = new HashMap<>();
    mAliasSubListMap = new HashMap<>();

    final ArrayAdapter<String> comboboxAdapter = new ArrayAdapter<>(getContext(),
            R.layout.formtemplate_double_spinner);
    setAdapter(comboboxAdapter);

    if (values != null) {
        for (int j = 0; j < values.length(); j++) {
            JSONObject keyValue = values.getJSONObject(j);
            String value = keyValue.getString(JSON_VALUE_NAME_KEY);
            String valueAlias = keyValue.getString(JSON_VALUE_ALIAS_KEY);

            Map<String, String> subAliasValueMap = new HashMap<>();
            AliasList subAliasList = new AliasList();

            mAliasValueMap.put(valueAlias, value);
            mSubAliasValueMaps.put(valueAlias, subAliasValueMap);
            mAliasSubListMap.put(valueAlias, subAliasList);
            comboboxAdapter.add(valueAlias);

            if (keyValue.has(JSON_DEFAULT_KEY) && keyValue.getBoolean(JSON_DEFAULT_KEY))
                defaultPosition = j;

            if (null != lastValue && lastValue.equals(value)) // if modify data
                lastValuePosition = j;

            JSONArray subValues = keyValue.getJSONArray(JSON_VALUES_KEY);
            for (int k = 0; k < subValues.length(); k++) {
                JSONObject subKeyValue = subValues.getJSONObject(k);
                String subValue = subKeyValue.getString(JSON_VALUE_NAME_KEY);
                String subValueAlias = subKeyValue.getString(JSON_VALUE_ALIAS_KEY);

                subAliasValueMap.put(subValueAlias, subValue);
                subAliasList.aliasList.add(subValueAlias);

                if (subKeyValue.has(JSON_DEFAULT_KEY) && subKeyValue.getBoolean(JSON_DEFAULT_KEY))
                    subAliasList.defaultPosition = k;

                if (null != subLastValue && subLastValue.equals(subValue)) { // if modify data
                    lastValuePosition = j;
                    subLastValuePosition = k;
                }
            }
        }
    }

    setSelection(lastValuePosition >= 0 ? lastValuePosition : defaultPosition);
    final int subLastValuePositionFinal = subLastValuePosition;

    // The drop down view
    comboboxAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    float minHeight = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14,
            getResources().getDisplayMetrics());
    setPadding(0, (int) minHeight, 0, (int) minHeight);
    mSubCombobox.setPadding(0, (int) minHeight, 0, (int) minHeight);

    setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selectedValueAlias = comboboxAdapter.getItem(position);
            AliasList subAliasList = mAliasSubListMap.get(selectedValueAlias);

            ArrayAdapter<String> subComboboxAdapter = new ArrayAdapter<>(view.getContext(),
                    R.layout.formtemplate_double_spinner, subAliasList.aliasList);
            subComboboxAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            mSubCombobox.setAdapter(subComboboxAdapter);
            mSubCombobox.setSelection(mFirstShow && subLastValuePositionFinal >= 0 ? subLastValuePositionFinal
                    : subAliasList.defaultPosition);

            if (mFirstShow) {
                mFirstShow = false;
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
}

From source file:org.bohrmeista.chan.ui.activity.BoardActivity.java

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

    ChanApplication.getBoardManager().addListener(this);

    boardLoadable = new Loadable();
    threadLoadable = new Loadable();

    boardFragment = ThreadFragment.newInstance(this);
    setBoardFragmentViewMode();//from w w w. j a  v a2s.  c  om

    threadFragment = ThreadFragment.newInstance(this);

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.replace(R.id.left_pane, boardFragment);
    ft.replace(R.id.right_pane, threadFragment);
    ft.commitAllowingStateLoss();

    final ActionBar actionBar = getActionBar();

    boardSpinner = new Spinner(actionBar.getThemedContext());
    spinnerAdapter = new BoardSpinnerAdapter(this, boardSpinner);
    boardSpinner.setAdapter(spinnerAdapter);
    boardSpinner.setOnItemSelectedListener(this);

    actionBar.setCustomView(boardSpinner);
    actionBar.setDisplayShowCustomEnabled(true);

    updatePaneState();

    Intent startIntent = getIntent();
    Uri startUri = startIntent.getData();

    if (savedInstanceState != null) {
        threadLoadable.readFromBundle(this, "thread", savedInstanceState);
        startLoadingThread(threadLoadable);

        // Reset page etc.
        Loadable tmp = new Loadable();
        tmp.readFromBundle(this, "board", savedInstanceState);
        startLoadingBoard(new Loadable(tmp.board));
    } else {
        if (startUri != null) {
            handleIntentURI(startUri);
        }

        if (boardLoadable.mode == Loadable.Mode.INVALID) {
            List<Board> savedValues = ChanApplication.getBoardManager().getSavedBoards();
            if (savedValues.size() > 0) {
                startLoadingBoard(new Loadable(savedValues.get(0).value));
            }
        }
    }

    if (startIntent.getExtras() != null) {
        handleExtraBundle(startIntent.getExtras());
    }

    ignoreNextOnItemSelected = true;
}

From source file:se.eliga.aves.birddetail.BirdDetailsTabActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bird_details_tab_layout);

    final String latinSpecies = getIntent().getExtras().getString(BirdListFragment.LATIN_SPECIES);
    final String englishSpecies = getIntent().getExtras().getString(BirdListFragment.ENGLISH_SPECIES);
    final String swedishFamily = getIntent().getExtras().getString(BirdListFragment.SWEDISH_FAMILY);

    Bundle bundle = new Bundle(1);
    bundle.putString(BirdSpeciesWebFragment.ENGLISH_SPECIES, englishSpecies);
    bundle.putString(BirdSpeciesXenoCantoPlayerFragment.LATIN_SPECIES, latinSpecies);

    tabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
    tabHost.setup(this, getSupportFragmentManager(), R.id.tabFrameLayout);

    tabHost.addTab(//w  ww  .  jav  a  2 s  . com
            tabHost.newTabSpec("Wikipedia").setIndicator(getText(R.string.tab_wikipedia),
                    getResources().getDrawable(android.R.drawable.star_on)),
            BirdSpeciesWebFragment.class, bundle);
    tabHost.addTab(
            tabHost.newTabSpec("Flickr").setIndicator(getText(R.string.tab_photos),
                    getResources().getDrawable(android.R.drawable.star_on)),
            BirdSpeciesFlickrGalleryFragment.class, bundle);
    tabHost.addTab(
            tabHost.newTabSpec("xeno-canto").setIndicator(getText(R.string.tab_sounds),
                    getResources().getDrawable(android.R.drawable.star_on)),
            BirdSpeciesXenoCantoPlayerFragment.class, bundle);
    tabHost.addTab(
            tabHost.newTabSpec("Statistik").setIndicator(getText(R.string.tab_facts),
                    getResources().getDrawable(android.R.drawable.star_on)),
            BirdSpeciesFactsFragment.class, bundle);
    tabHost.addTab(tabHost.newTabSpec("Karta").setIndicator(getText(R.string.tab_map),
            getResources().getDrawable(android.R.drawable.star_on)), MapFragment.class, bundle);

    TabWidget tabWidget = (TabWidget) findViewById(android.R.id.tabs);
    LinearLayout linearLayout = (LinearLayout) tabWidget.getParent();
    HorizontalScrollView horizontalScrollView = new HorizontalScrollView(this);
    horizontalScrollView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,
            FrameLayout.LayoutParams.WRAP_CONTENT));
    linearLayout.addView(horizontalScrollView, 0);
    linearLayout.removeView(tabWidget);
    horizontalScrollView.addView(tabWidget);
    horizontalScrollView.setHorizontalScrollBarEnabled(false);

    BirdListSpinnerAdapter birdListSpinnerAdapter = createAdapter();
    birdListSpinnerAdapter.setFilterFamily(swedishFamily);
    birdListSpinnerAdapter.initialize(getSharedPreferences(Constants.BIRD_APP_SETTINGS, Context.MODE_PRIVATE));
    if (BirdListAdapter.SortOption.PHYLOGENETIC.equals(birdListSpinnerAdapter.getSortOption())) {
        birdListSpinnerAdapter.setSortOption(BirdListAdapter.SortOption.SWEDISH);
    }

    birdListSpinnerAdapter.refresh();
    birdListSpinnerAdapter.notifyDataSetChanged();

    Spinner spinner = new Spinner(this);
    spinner.setId(R.id.birdspecies_spinner);
    spinner.setAdapter(birdListSpinnerAdapter);
    spinner.setGravity(Gravity.FILL_HORIZONTAL);

    spinner.setSelection(birdListSpinnerAdapter.getPosition(new Bird(latinSpecies)));
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            BirdSpeciesFragment fragment = (BirdSpeciesFragment) getSupportFragmentManager()
                    .findFragmentByTag(tabHost.getCurrentTabTag());
            Spinner spinner = (Spinner) getActionBar().getCustomView().findViewById(R.id.birdspecies_spinner);
            fragment.loadBird((Bird) spinner.getSelectedItem());
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
        }
    });
    getActionBar().setCustomView(spinner);
    getActionBar().setDisplayOptions(
            ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_CUSTOM);

}

From source file:net.pocketmagic.android.eventinjector.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(LT, "App created.");
    Events.intEnableDebug(1);/*from  ww  w.  j  av a  2s.  co m*/
    // disable the titlebar
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    // create a basic user interface
    LinearLayout panel = new LinearLayout(this);
    panel.setOrientation(LinearLayout.VERTICAL);
    setContentView(panel);

    EditText v = new EditText(this);
    v.setId(idTextView);
    v.setOnClickListener(this);
    panel.addView(v);

    // --
    Button b = new Button(this);
    b.setText("Scan Input Devs");
    b.setId(idButScan);
    b.setOnClickListener(this);
    panel.addView(b);

    // put list in a scroll view
    LinearLayout listLayout = new LinearLayout(this);
    listLayout.setLayoutParams(
            new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1.0f));
    m_lvDevices = new ListView(this);
    LayoutParams lvLayoutParam = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
    m_lvDevices.setLayoutParams(lvLayoutParam);
    m_lvDevices.setId(idLVDevices);
    m_lvDevices.setDividerHeight(0);
    m_lvDevices.setFadingEdgeLength(0);
    m_lvDevices.setCacheColorHint(0);
    m_lvDevices.setAdapter(null);

    listLayout.addView(m_lvDevices);
    panel.addView(listLayout);
    // --
    LinearLayout panelH = new LinearLayout(this);
    panelH.setOrientation(LinearLayout.HORIZONTAL);
    panel.addView(panelH);
    // --
    m_selDevSpinner = new Spinner(this);
    m_selDevSpinner.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    m_selDevSpinner.setId(idSelSpin);
    m_selDevSpinner.setOnItemSelectedListener((OnItemSelectedListener) this);
    panelH.addView(m_selDevSpinner);
    // -- simulate key event
    b = new Button(this);
    b.setText(">Key");
    b.setId(idButInjectKey);
    b.setOnClickListener(this);
    panelH.addView(b);
    // -- simulate touch event
    b = new Button(this);
    b.setText(">Tch");
    b.setId(idButInjectTouch);
    b.setOnClickListener(this);
    panelH.addView(b);
    // --
    m_tvMonitor = new TextView(this);
    m_tvMonitor.setText("Event Monitor stopped.");
    panel.addView(m_tvMonitor);
    // --
    panelH = new LinearLayout(this);
    panelH.setOrientation(LinearLayout.HORIZONTAL);
    panel.addView(panelH);
    // --
    b = new Button(this);
    b.setText("Monitor Start");
    b.setId(idButMonitorStart);
    b.setOnClickListener(this);
    panelH.addView(b);
    // --
    b = new Button(this);
    b.setText("Monitor Stop");
    b.setId(idButMonitorStop);
    b.setOnClickListener(this);
    panelH.addView(b);
    // -- simulate test event
    b = new Button(this);
    b.setText(">Test");
    b.setId(idButTest);
    b.setOnClickListener(this);
    panelH.addView(b);
}

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 ww  . ja  v  a 2s  .co  m*/
            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:com.hichinaschool.flashcards.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 a  2s  .  c  o  m
            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);

    Button btnDone = new Button(this);
    btnDone.setText(getText(R.string.multimedia_editor_trans_translate));
    btnDone.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            translate();
        }
    });

    linearLayout.addView(btnDone);

}