Example usage for android.widget ArrayAdapter createFromResource

List of usage examples for android.widget ArrayAdapter createFromResource

Introduction

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

Prototype

public static @NonNull ArrayAdapter<CharSequence> createFromResource(@NonNull Context context,
        @ArrayRes int textArrayResId, @LayoutRes int textViewResId) 

Source Link

Document

Creates a new ArrayAdapter from external resources.

Usage

From source file:com.tencent.wstt.gt.activity.GTLogFragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View logLayout = inflater.inflate(R.layout.gt_logactivity, container, false);
    displayWidth = DeviceUtils.getDisplayWidth(getActivity());

    rl_log_filter = (RelativeLayout) logLayout.findViewById(R.id.rl_log_filter);

    cb_logcatSwitch = (GTCheckBox) logLayout.findViewById(R.id.cb_logcat_switch);
    cb_logcatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override/*from  www .j av  a2 s  . c  om*/
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                // TODO logcat?
                logcatTask = new LogcatRunnable();
                new Thread(logcatTask).start();
            } else {
                logcatTask.killReader();
            }
        }
    });

    btn_delete = (ImageButton) logLayout.findViewById(R.id.gtlog_delete);
    btn_save = (ImageButton) logLayout.findViewById(R.id.gtlog_save);
    btn_open = (ImageButton) logLayout.findViewById(R.id.gtlog_open);

    btn_level_toast = (ImageButton) logLayout.findViewById(R.id.log_level_toast);
    btn_tag_toast = (ImageButton) logLayout.findViewById(R.id.log_tag_toast);

    /*
     * ??ImageView ??filterListViewfilterListView
     */
    img_empty = (ImageView) logLayout.findViewById(R.id.view_empty);
    img_empty.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            img_empty.setVisibility(View.GONE);
            filterListView.setVisibility(View.GONE);
            cancelFilterMsgInput(v);
            return false;
        }
    });

    /*
     * ?
     */
    RelativeLayout rl_save = (RelativeLayout) LayoutInflater.from(getActivity())
            .inflate(R.layout.gt_dailog_save, null, false);
    ImageButton btn_cleanSavePath = (ImageButton) rl_save.findViewById(R.id.save_clean);
    btn_cleanSavePath.setOnClickListener(this);

    et_savePath = (EditText) rl_save.findViewById(R.id.save_editor);
    String lastSaveLog = GTLogInternal.getLastSaveLog();
    if (lastSaveLog != null && lastSaveLog.contains(".") && lastSaveLog.endsWith(LogUtils.LOG_POSFIX)) {
        lastSaveLog = lastSaveLog.substring(0, lastSaveLog.lastIndexOf("."));
    }
    et_savePath.setText(lastSaveLog);
    dlg_save = new Builder(getActivity()).setTitle(getString(R.string.save_file)).setView(rl_save)
            .setPositiveButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).setNegativeButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // ??
                    String path = et_savePath.getText().toString();
                    try {
                        File f = null;
                        if (FileUtil.isPathStringValid(path)) {
                            String validPath = FileUtil.convertValidFilePath(path, LogUtils.LOG_POSFIX);
                            if (FileUtil.isPath(validPath)) {
                                f = new File(validPath);
                                f.mkdirs();
                            } else {
                                f = new File(Env.ROOT_LOG_FOLDER, validPath);
                            }
                            GTLogInternal.setLastSaveLog(validPath);
                        }

                        if (f.exists()) {
                            f.delete();
                        }

                        LogUtils.writeLog(logAdapter.getUIEntryList(), f, false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    dialog.dismiss();
                }

            }).create();

    btn_save.setOnClickListener(this);

    // 
    btn_delete.setOnClickListener(this);

    // 
    btn_open.setOnClickListener(this);

    // 
    rl_loglist = (RelativeLayout) logLayout.findViewById(R.id.rl_loglist);
    listView = (ListView) logLayout.findViewById(R.id.loglist);
    initCurLogAdapter();
    logAdapter.setFilter();
    listView.setAdapter(logAdapter);
    // button???
    listView.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            rl_log_filter.setVisibility(View.GONE);
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (visibleItemCount + firstVisibleItem == totalItemCount) {
                logAdapter.setAutoRefresh(true);
            } else {
                logAdapter.setAutoRefresh(false);
            }
        }
    });
    // button?
    rl_loglist.setOnClickListener(this);
    listView.setOnTouchListener(logListTouchListener);

    // ?
    filterListView = (ListView) logLayout.findViewById(R.id.spinner_list);
    tagAdapter = new ArrayAdapter<String>(getActivity(), R.layout.gt_simple_dropdown_item);
    filterListView.setAdapter(tagAdapter);

    filterListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long arg3) {
            img_empty.setVisibility(View.GONE);
            filterListView.setVisibility(View.GONE);

            if (parent.getAdapter() == tagAdapter) {
                if (position == 0)
                    GTLogInternal.setCurFilterTag("");
                else
                    GTLogInternal.setCurFilterTag((String) parent.getAdapter().getItem(position));

                btn_tag.setText(tagAdapter.getItem(position));
            } else if (parent.getAdapter() instanceof MsgAdaptor) {
                String sCurSelectedMsg = (String) parent.getAdapter().getItem(position);
                LinkedList<String> curShowDownMsgList = GTLogInternal.getCurFilterShowDownMsgList();
                LinkedList<String> msgHistory = GTLogInternal.getCurFilterMsgHistory();

                GTLogInternal.setCurFilterMsg(sCurSelectedMsg);
                msgWatched = false;
                et_Msg.removeTextChangedListener(msg_watcher);
                String s = curShowDownMsgList.remove(position);

                curShowDownMsgList.addFirst(s);
                msgHistory.remove(s);
                msgHistory.addFirst(s);
                et_Msg.setText(sCurSelectedMsg);
                btn_msg_clear.setVisibility(View.VISIBLE);
                cancelFilterMsgInput(parent);
            } else {
                GTLogInternal.setCurFilterLevel(position);
                btn_level.setText(levelAdapter.getItem(position));
            }

            onLogChanged();
        }
    });

    // Activity???
    GTLogInternal.addLogListener(this);

    // ?

    //btn_search = (ImageButton) findViewById(R.id.log_search);

    btn_search = (ImageButton) logLayout.findViewById(R.id.gtlog_search);
    btn_search.setOnClickListener(this);

    // 
    btn_level = (Button) logLayout.findViewById(R.id.log_level);
    levelAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.log_level,
            R.layout.gt_simple_dropdown_item);
    btn_level.setText(levelAdapter.getItem(GTLogInternal.getCurFilterLevel()));

    btn_level.setOnClickListener(this);

    // TAG
    btn_tag = (Button) logLayout.findViewById(R.id.log_tag);
    if (GTLogInternal.getCurFilterTag().length() == 0) {
        btn_tag.setText("TAG");
    } else {
        btn_tag.setText(GTLogInternal.getCurFilterTag());
    }

    btn_tag.setOnClickListener(this);

    // 
    et_Msg = (EditText) logLayout.findViewById(R.id.log_msg);
    et_Msg.setText(GTLogInternal.getCurFilterMsg());

    et_Msg.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus && !logAdapter.isEmpty())// edit?
            {
                msgEtOnFocusOrClick();
            }
        }
    });

    et_Msg.setOnClickListener(this);

    et_Msg.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            switch (keyCode) {
            case KeyEvent.KEYCODE_ENTER:
                // ?showdown?
                msgWatched = false;
                et_Msg.removeTextChangedListener(msg_watcher);

                String word = et_Msg.getText().toString();
                if (!word.equals("")) {
                    LinkedList<String> curShowDownMsgList = GTLogInternal.getCurFilterShowDownMsgList();
                    LinkedList<String> msgHistory = GTLogInternal.getCurFilterMsgHistory();

                    msgHistory.remove(word);
                    msgHistory.addFirst(word);
                    curShowDownMsgList.remove(word);
                    curShowDownMsgList.addFirst(word);
                }

                filterListView.setVisibility(View.GONE);
                img_empty.setVisibility(View.GONE);

                cancelFilterMsgInput(v);

                return true;
            }
            return false;
        }
    });

    // ?
    btn_msg_clear = (ImageButton) logLayout.findViewById(R.id.log_msg_clear);
    btn_msg_clear.setOnClickListener(this);

    if (et_Msg.getText().toString().length() > 0) {
        btn_msg_clear.setVisibility(View.VISIBLE);
    } else {
        btn_msg_clear.setVisibility(View.GONE);
    }

    // ?
    btn_msg_input_cancel = (Button) logLayout.findViewById(R.id.log_msg_cancel);
    btn_msg_input_cancel.setOnClickListener(this);

    handler = new Handler();

    return logLayout;
}

From source file:org.noise_planet.noisecapture.CalibrationLinearityActivity.java

private void initScatter() {
    final ScatterChart scatterChart = getScatterChart();
    if (scatterChart == null) {
        return;/*from  w w w .  j  a  v a2s  . co m*/
    }
    scatterChart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Show
            AlertDialog.Builder builder = new AlertDialog.Builder(CalibrationLinearityActivity.this);
            builder.setTitle(CalibrationLinearityActivity.this.getText(R.string.calibration_select_frequency));
            ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                    CalibrationLinearityActivity.this, R.array.calibrate_type_list_array,
                    android.R.layout.simple_selectable_list_item);
            builder.setAdapter(adapter,
                    new ItemActionOnClickListener(CalibrationLinearityActivity.this, scatterChart));
            builder.show();
        }
    });

    scatterChart.setDescription("");

    scatterChart.setDrawGridBackground(false);

    scatterChart.setMaxVisibleValueCount(200);

    Legend l = scatterChart.getLegend();
    l.setPosition(Legend.LegendPosition.RIGHT_OF_CHART);
    l.setTextColor(Color.WHITE);

    YAxis yl = scatterChart.getAxisLeft();
    yl.setTextColor(Color.WHITE);
    yl.setGridColor(Color.WHITE);
    scatterChart.getAxisRight().setEnabled(false);

    XAxis xl = scatterChart.getXAxis();
    xl.setDrawGridLines(false);
    xl.setTextColor(Color.WHITE);
    xl.setGridColor(Color.WHITE);
}

From source file:com.terraremote.terrafieldreport.OpenGroundReport.java

@OnItemSelected(R.id.checkInContactRoleSpinner)
void otherSpinnerSelected(int position) {
    position = mCheckInContactRoleSpinner.getSelectedItemPosition();
    if (position == 4) {
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(OpenGroundReport.this,
                R.array.check_in_contact_other, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mCheckInContactNameSpinner.setVisibility(View.GONE);
        mOtherContactName.setVisibility(View.VISIBLE);
        // Apply the adapter to the spinner
        mCheckInContactNameSpinner.setAdapter(adapter);
    }//from   w w w . j a  v a  2  s.  c  o  m
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    super.onCreate(savedInstanceState);

    // HockeyApp//from  ww w  .  ja  va  2 s  .  c o m
    try {
        MetricsManager.register(getApplication());
    } catch (Exception e) {
        Log.e(TAG, e.getMessage());
    }

    //Log.i(TAG, "OnCreated called");
    setContentView(R.layout.stats);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle(getString(R.string.app_name));

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayUseLogoEnabled(false);

    // set debugging
    if (sharedPrefs.getBoolean("debug_logging", false)) {
        LogSettings.DEBUG = true;
        CommonLogSettings.DEBUG = true;
    } else {
        LogSettings.DEBUG = false;
        CommonLogSettings.DEBUG = false;
    }

    swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);

    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            doRefresh(true);
        }
    });

    ///////////////////////////////////////////////
    // check if we have a new release
    ///////////////////////////////////////////////
    // if yes do some migration (if required) and show release notes
    String strLastRelease = sharedPrefs.getString("last_release", "0");

    String strCurrentRelease = "";
    try {
        PackageInfo pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);

        strCurrentRelease = Integer.toString(pinfo.versionCode);
    } catch (Exception e) {
        // nop strCurrentRelease is set to ""
    }

    // Grant permissions if they are missing and root is available
    if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)
            || !SysUtils.hasPackageUsageStatsPermission(this)) {
        if ((RootShell.getInstance().isRooted())) {

            // attempt to set perms using pm-comand
            Log.i(TAG, "attempting to grant perms with 'pm grant'");

            String pkg = this.getPackageName();
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.BATTERY_STATS");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.DUMP");
            RootShell.getInstance().run("pm grant " + pkg + " android.permission.PACKAGE_USAGE_STATS");

            if (SysUtils.hasBatteryStatsPermission(this)) {
                Log.i(TAG, "succeeded");
            } else {
                Log.i(TAG, "failed");
            }
        }
    }

    // Package usage stats were introduced in SDK21 so we need to make the distinction
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // show install as system app screen if root available but perms missing
        if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)
                || !SysUtils.hasPackageUsageStatsPermission(this)) {
            Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
            this.startActivity(intentSystemApp);
        }
    } else {
        if (!SysUtils.hasBatteryStatsPermission(this) || !SysUtils.hasDumpsysPermission(this)) {
            Intent intentSystemApp = new Intent(this, SystemAppActivity.class);
            this.startActivity(intentSystemApp);
        }

    }
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // first start
    if (strLastRelease.equals("0")) {

        boolean firstLaunch = !prefs.getBoolean("launched", false);

        if (firstLaunch) {
            // Save that the app has been launched
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("launched", true);
            editor.commit();

            // start service to persist reference
            Intent serviceIntent = new Intent(this, WriteUnpluggedReferenceService.class);
            this.startService(serviceIntent);

            // refresh widgets
            Intent intentRefreshWidgets = new Intent(LargeWidgetProvider.WIDGET_UPDATE);
            this.sendBroadcast(intentRefreshWidgets);

        }

        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();
    } else if (!strLastRelease.equals(strCurrentRelease)) {
        // save the current release to properties so that the dialog won't be shown till next version
        SharedPreferences.Editor updater = sharedPrefs.edit();
        updater.putString("last_release", strCurrentRelease);
        updater.commit();

        // we don't need to delete refs as long as we don't change the database schema
        //         Toast.makeText(this, getString(R.string.info_deleting_refs), Toast.LENGTH_SHORT).show();
        //         ReferenceStore.deleteAllRefs(this);
        //         Intent i = new Intent(this, WriteBootReferenceService.class);
        //         this.startService(i);
        //         i = new Intent(this, WriteUnpluggedReferenceService.class);
        //         this.startService(i);
        ChangeLog cl = new ChangeLog(this);
        cl.getLogDialog().show();

    }

    ///////////////////////////////////////////////
    // retrieve default selections for spinners
    // if none were passed
    ///////////////////////////////////////////////

    m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
    m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);

    if (!ReferenceStore.hasReferenceByName(m_refFromName, this)) {

        m_refFromName = Reference.BOOT_REF_FILENAME;
        Toast.makeText(this, getString(R.string.info_fallback_to_boot), Toast.LENGTH_SHORT).show();
    }

    if (LogSettings.DEBUG)
        Log.i(TAG, "onCreate state from preferences: refFrom=" + m_refFromName + " refTo=" + m_refToName);

    try {
        // recover any saved state
        if ((savedInstanceState != null) && (!savedInstanceState.isEmpty())) {
            m_iStat = (Integer) savedInstanceState.getSerializable("stat");
            m_refFromName = (String) savedInstanceState.getSerializable("stattypeFrom");
            m_refToName = (String) savedInstanceState.getSerializable("stattypeTo");

            if (LogSettings.DEBUG)
                Log.i(TAG,
                        "onCreate retrieved saved state: refFrom=" + m_refFromName + " refTo=" + m_refToName);

        }
    } catch (Exception e) {
        m_iStat = Integer.valueOf(sharedPrefs.getString("default_stat", "0"));
        m_refFromName = sharedPrefs.getString("default_stat_type", Reference.UNPLUGGED_REF_FILENAME);

        Log.e(TAG, "Exception: " + e.getMessage());
        DataStorage.LogToFile(LOGFILE, "Exception in onCreate restoring Bundle");
        DataStorage.LogToFile(LOGFILE, e.getMessage());
        DataStorage.LogToFile(LOGFILE, e.getStackTrace());

        Toast.makeText(this, getString(R.string.info_state_recovery_error), Toast.LENGTH_SHORT).show();
    }

    // Handle the case the Activity was called from an intent with paramaters
    Bundle extras = getIntent().getExtras();
    if ((extras != null) && !extras.isEmpty()) {
        // Override if some values were passed to the intent
        if (extras.containsKey(StatsActivity.STAT))
            m_iStat = extras.getInt(StatsActivity.STAT);
        if (extras.containsKey(StatsActivity.STAT_TYPE_FROM))
            m_refFromName = extras.getString(StatsActivity.STAT_TYPE_FROM);
        if (extras.containsKey(StatsActivity.STAT_TYPE_TO))
            m_refToName = extras.getString(StatsActivity.STAT_TYPE_TO);

        if (LogSettings.DEBUG)
            Log.i(TAG, "onCreate state from extra: refFrom=" + m_refFromName + " refTo=" + m_refToName);

        boolean bCalledFromNotification = extras.getBoolean(StatsActivity.FROM_NOTIFICATION, false);

        // Clear the notifications that was clicked to call the activity
        if (bCalledFromNotification) {
            NotificationManager nM = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
            nM.cancel(EventWatcherService.NOTFICATION_ID);
        }
    }

    // Spinner for selecting the stat
    Spinner spinnerStat = (Spinner) findViewById(R.id.spinnerStat);

    ArrayAdapter spinnerStatAdapter = ArrayAdapter.createFromResource(this, R.array.stats,
            R.layout.bbs_spinner_layout); //android.R.layout.simple_spinner_item);
    spinnerStatAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item); // android.R.layout.simple_spinner_dropdown_item);

    spinnerStat.setAdapter(spinnerStatAdapter);
    // setSelection MUST be called after setAdapter
    spinnerStat.setSelection(m_iStat);
    spinnerStat.setOnItemSelectedListener(this);

    ///////////////////////////////////////////////
    // Spinner for Selecting the Stat type
    ///////////////////////////////////////////////
    Spinner spinnerStatType = (Spinner) findViewById(R.id.spinnerStatType);
    m_spinnerFromAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout); //android.R.layout.simple_spinner_item);
    m_spinnerFromAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item); //android.R.layout.simple_spinner_dropdown_item);
    spinnerStatType.setAdapter(m_spinnerFromAdapter);

    try {
        this.setListViewAdapter();
    } catch (BatteryInfoUnavailableException e) {
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Snackbar.make(findViewById(android.R.id.content), R.string.info_service_connection_error,
                Snackbar.LENGTH_LONG).show();
        //         Toast.makeText(this,
        //               getString(R.string.info_service_connection_error),
        //               Toast.LENGTH_LONG).show();

    } catch (Exception e) {
        //Log.e(TAG, e.getMessage(), e.fillInStackTrace());
        Log.e(TAG, "Exception: " + Log.getStackTraceString(e));
        Toast.makeText(this, getString(R.string.info_unknown_stat_error), Toast.LENGTH_LONG).show();
    }
    // setSelection MUST be called after setAdapter
    spinnerStatType.setSelection(m_spinnerFromAdapter.getPosition(m_refFromName));
    spinnerStatType.setOnItemSelectedListener(this);

    ///////////////////////////////////////////////
    // Spinner for Selecting the end sample
    ///////////////////////////////////////////////
    Spinner spinnerStatSampleEnd = (Spinner) findViewById(R.id.spinnerStatSampleEnd);
    m_spinnerToAdapter = new ReferencesAdapter(this, R.layout.bbs_spinner_layout); //android.R.layout.simple_spinner_item);
    m_spinnerToAdapter.setDropDownViewResource(R.layout.bbs_spinner_dropdown_item); //android.R.layout.simple_spinner_dropdown_item);

    spinnerStatSampleEnd.setVisibility(View.VISIBLE);
    spinnerStatSampleEnd.setAdapter(m_spinnerToAdapter);
    // setSelection must be called after setAdapter
    if ((m_refToName != null) && !m_refToName.equals("")) {
        int pos = m_spinnerToAdapter.getPosition(m_refToName);
        spinnerStatSampleEnd.setSelection(pos);

    } else {
        spinnerStatSampleEnd.setSelection(m_spinnerToAdapter.getPosition(Reference.CURRENT_REF_FILENAME));
    }

    spinnerStatSampleEnd.setOnItemSelectedListener(this);

    ///////////////////////////////////////////////
    // sorting
    ///////////////////////////////////////////////
    m_iSorting = 0;

    // log reference store
    ReferenceStore.logReferences(this);

    if (LogSettings.DEBUG) {
        Log.i(TAG, "onCreate final state: refFrom=" + m_refFromName + " refTo=" + m_refToName);
        Log.i(TAG, "OnCreated end");
    }

}

From source file:org.onebusaway.android.ui.TripPlanFragment.java

private void advancedSettings() {

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());

    final TypedArray transitModeResource = getContext().getResources()
            .obtainTypedArray(R.array.transit_mode_array);
    final boolean unitsAreImperial = !PreferenceUtils.getUnitsAreMetricFromPreferences(getContext());

    dialogBuilder.setTitle(R.string.trip_plan_advanced_settings)
            .setView(R.layout.trip_plan_advanced_settings_dialog);

    dialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        @Override//  w ww.  j a  v a2s. c o  m
        public void onClick(DialogInterface dialogInterface, int which) {

            Dialog dialog = (Dialog) dialogInterface;

            boolean optimizeTransfers = ((CheckBox) dialog.findViewById(R.id.checkbox_minimize_transfers))
                    .isChecked();

            Spinner spinnerTravelBy = (Spinner) dialog.findViewById(R.id.spinner_travel_by);

            int modeId = transitModeResource.getResourceId(spinnerTravelBy.getSelectedItemPosition(), 0);

            boolean wheelchair = ((CheckBox) dialog.findViewById(R.id.checkbox_wheelchair_acccesible))
                    .isChecked();

            String maxWalkString = ((EditText) dialog.findViewById(R.id.number_maximum_walk_distance)).getText()
                    .toString();
            double maxWalkDistance;
            if (TextUtils.isEmpty(maxWalkString)) {
                maxWalkDistance = Double.MAX_VALUE;
            } else {
                double d = Double.parseDouble(maxWalkString);
                maxWalkDistance = unitsAreImperial ? ConversionUtils.feetToMeters(d) : d;
            }

            mBuilder.setOptimizeTransfers(optimizeTransfers).setModeSetById(modeId)
                    .setWheelchairAccessible(wheelchair).setMaxWalkDistance(maxWalkDistance);

            checkRequestAndSubmit();
        }
    });

    final AlertDialog dialog = dialogBuilder.create();

    dialog.show();

    CheckBox minimizeTransfersCheckbox = (CheckBox) dialog.findViewById(R.id.checkbox_minimize_transfers);
    Spinner spinnerTravelBy = (Spinner) dialog.findViewById(R.id.spinner_travel_by);
    CheckBox wheelchairCheckbox = (CheckBox) dialog.findViewById(R.id.checkbox_wheelchair_acccesible);
    EditText maxWalkEditText = (EditText) dialog.findViewById(R.id.number_maximum_walk_distance);

    minimizeTransfersCheckbox.setChecked(mBuilder.getOptimizeTransfers());

    wheelchairCheckbox.setChecked(mBuilder.getWheelchairAccessible());

    ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(), R.array.transit_mode_array,
            android.R.layout.simple_spinner_item);

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

    int modeSetId = mBuilder.getModeSetId();
    if (modeSetId != -1) {
        for (int i = 0; i < transitModeResource.length(); i++) {
            if (transitModeResource.getResourceId(i, -1) == modeSetId) {
                spinnerTravelBy.setSelection(i);
                break;
            }
        }
    }

    Double maxWalk = mBuilder.getMaxWalkDistance();
    if (maxWalk != null && Double.MAX_VALUE != maxWalk) {
        if (unitsAreImperial) {
            maxWalk = ConversionUtils.metersToFeet(maxWalk);
        }
        maxWalkEditText.setText(String.format("%d", maxWalk.longValue()));
    }

    if (unitsAreImperial) {
        TextView label = (TextView) dialog.findViewById(R.id.label_minimum_walk_distance);
        label.setText(getString(R.string.feet_abbreviation));
    }
}

From source file:biz.incomsystems.fwknop2.ConfigDetailFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_config_detail, container, false);
    active_Nick = getArguments().getString("item_id");
    myJuice = new PluginContract();

    //Handlers for the input fields
    txt_NickName = (TextView) rootView.findViewById(R.id.NickName);
    txt_allowIP = (TextView) rootView.findViewById(R.id.iptoallow);
    lay_allowIP = (LinearLayout) rootView.findViewById(R.id.iptoallowsl);
    lay_natIP = (LinearLayout) rootView.findViewById(R.id.natipsl);
    lay_natport = (LinearLayout) rootView.findViewById(R.id.natportsl);
    lay_serverCMD = (LinearLayout) rootView.findViewById(R.id.servercmdsl);
    txt_ports = (TextView) rootView.findViewById(R.id.AccessPorts);
    txt_server_ip = (TextView) rootView.findViewById(R.id.destIP);
    txt_server_port = (TextView) rootView.findViewById(R.id.destPort);
    txt_server_time = (TextView) rootView.findViewById(R.id.fwTimeout);
    txt_server_cmd = (TextView) rootView.findViewById(R.id.servercmd);
    txt_nat_ip = (TextView) rootView.findViewById(R.id.natip);
    txt_nat_port = (TextView) rootView.findViewById(R.id.natport);
    lay_AccessPort = (LinearLayout) rootView.findViewById(R.id.AccessPortsl);
    lay_fwTimeout = (LinearLayout) rootView.findViewById(R.id.fwTimeoutl);
    lay_sshcmd = (LinearLayout) rootView.findViewById(R.id.sshcmdsl);
    txt_ssh_cmd = (TextView) rootView.findViewById(R.id.sshcmd);
    txt_KEY = (TextView) rootView.findViewById(R.id.passwd);
    txt_HMAC = (TextView) rootView.findViewById(R.id.hmac);
    chkb64hmac = (CheckBox) rootView.findViewById(R.id.chkb64hmac);
    chkb64key = (CheckBox) rootView.findViewById(R.id.chkb64key);

    spn_juice = (Spinner) rootView.findViewById(R.id.juice_spn);
    juice_adapt = new ConnectionSpinnerAdapter(getActivity());
    spn_juice.setAdapter(juice_adapt);/* w  w  w  . ja  v a  2 s . c o  m*/

    spn_allowip = (Spinner) rootView.findViewById(R.id.allowip);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.spinner_options,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spn_allowip.setAdapter(adapter);
    spn_allowip.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            if (parent.getItemAtPosition(pos).toString().equalsIgnoreCase("Allow IP")) {
                lay_allowIP.setVisibility(View.VISIBLE);
            } else {
                lay_allowIP.setVisibility(View.GONE);
            }
        }

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

    spn_ssh = (Spinner) rootView.findViewById(R.id.ssh);
    ArrayAdapter<CharSequence> adapter_ssh = ArrayAdapter.createFromResource(getActivity(), R.array.ssh_options,
            android.R.layout.simple_spinner_item);
    adapter_ssh.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spn_ssh.setAdapter(adapter_ssh);
    spn_ssh.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // An item was selected. You can retrieve the selected item using
            // parent.getItemAtPosition(pos)
            if (parent.getItemAtPosition(pos).toString().equalsIgnoreCase("None")) {
                lay_sshcmd.setVisibility(View.GONE);
                spn_juice.setVisibility(View.GONE);
                // blank the other options here
            } else if (parent.getItemAtPosition(pos).toString().equalsIgnoreCase("SSH Uri")) {
                // show the txt for the uri
                lay_sshcmd.setVisibility(View.VISIBLE);
                spn_juice.setVisibility(View.GONE);
            } else if (parent.getItemAtPosition(pos).toString().equalsIgnoreCase("Juicessh")) {
                lay_sshcmd.setVisibility(View.GONE);

                if (connectionListLoader == null) {
                    connectionListLoader = new ConnectionListLoader(getActivity(), juice_adapt);
                    connectionListLoader.setOnLoadedListener(new ConnectionListLoader.OnLoadedListener() {
                        @Override
                        public void onLoaded() { // This is so ugly...
                            spn_juice.setVisibility(View.VISIBLE);
                            if (config.SSH_CMD.contains("juice:") && spn_juice.getCount() > 0) {
                                for (int n = 0; n < spn_juice.getCount(); n++) {
                                    if (config.SSH_CMD.contains(juice_adapt.getConnectionName(n))) {
                                        spn_juice.setSelection(n);
                                    }
                                }
                            }
                        }
                    });
                    getActivity().getSupportLoaderManager().initLoader(0, null, connectionListLoader);
                } else {
                    getActivity().getSupportLoaderManager().restartLoader(0, null, connectionListLoader);
                }
            }
        }

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

    spn_configtype = (Spinner) rootView.findViewById(R.id.configtype);
    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(getActivity(),
            R.array.configtype_options, android.R.layout.simple_spinner_item);
    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spn_configtype.setAdapter(adapter2);
    spn_configtype.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            if (parent.getItemAtPosition(pos).toString().equalsIgnoreCase("Open Port")) {
                configtype = "Open Port";
                lay_AccessPort.setVisibility(View.VISIBLE);
                lay_fwTimeout.setVisibility(View.VISIBLE);
                txt_nat_ip.setText("");
                txt_nat_port.setText("");
                txt_server_cmd.setText("");
            } else {
                lay_AccessPort.setVisibility(View.GONE);
                lay_fwTimeout.setVisibility(View.GONE);
            }
            if (parent.getItemAtPosition(pos).toString().equalsIgnoreCase("Nat Access")) {
                configtype = "Nat Access";
                txt_server_cmd.setText("");
                lay_AccessPort.setVisibility(View.VISIBLE);
                lay_fwTimeout.setVisibility(View.VISIBLE);
                lay_natIP.setVisibility(View.VISIBLE);
                lay_natport.setVisibility(View.VISIBLE);
            } else {
                lay_natIP.setVisibility(View.GONE);
                lay_natport.setVisibility(View.GONE);
            }
            if (parent.getItemAtPosition(pos).toString().equalsIgnoreCase("Server Command")) {
                configtype = "Server Command";
                lay_serverCMD.setVisibility(View.VISIBLE);
                txt_ports.setText("");
                txt_nat_ip.setText("");
                txt_nat_port.setText("");
                txt_server_time.setText("");
            } else {
                lay_serverCMD.setVisibility(View.GONE);
            }
        }

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

    //Below is the loading of a saved config
    if (active_Nick.equalsIgnoreCase("")) {
        txt_NickName.setText("");
        config.SSH_CMD = "";
        txt_HMAC.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        txt_KEY.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    } else {
        config = mydb.getConfig(active_Nick);
        txt_NickName.setText(active_Nick);
        if (config.ACCESS_IP.equalsIgnoreCase("Resolve IP")) {
            spn_allowip.setSelection(0);
        } else if (config.ACCESS_IP.equalsIgnoreCase("0.0.0.0")) {
            spn_allowip.setSelection(1);
        } else {
            spn_allowip.setSelection(2);
            txt_allowIP.setText(config.ACCESS_IP);
        }
        txt_ports.setText(config.PORTS);
        txt_server_ip.setText(config.SERVER_IP);
        txt_server_port.setText(config.SERVER_PORT);
        txt_server_time.setText(config.SERVER_TIMEOUT);
        txt_KEY.setText(config.KEY);
        if (config.KEY_BASE64) {
            chkb64key.setChecked(true);
        } else {
            chkb64key.setChecked(false);
        }
        txt_HMAC.setText(config.HMAC);
        if (config.HMAC_BASE64) {
            chkb64hmac.setChecked(true);
        } else {
            chkb64hmac.setChecked(false);
        }
        if (!config.SERVER_CMD.equalsIgnoreCase("")) {
            spn_configtype.setSelection(2);
            txt_server_cmd.setText(config.SERVER_CMD);
        } else if (!config.NAT_IP.equalsIgnoreCase("")) {
            spn_configtype.setSelection(1);
            txt_ports.setText(config.PORTS);
            txt_nat_ip.setText(config.NAT_IP);
            txt_nat_port.setText(config.NAT_PORT);
            txt_server_time.setText(config.SERVER_TIMEOUT);
        } else {
            spn_configtype.setSelection(0);
        }
        if (config.SSH_CMD.equalsIgnoreCase("")) {
            spn_ssh.setSelection(0);
        } else if (config.SSH_CMD.contains("juice:")) {
            spn_ssh.setSelection(2);
        } else {
            spn_ssh.setSelection(1);
            txt_ssh_cmd.setText(config.SSH_CMD);
        }
    }
    return rootView;
}

From source file:com.glanznig.beepme.view.ExportActivity.java

private void populateFields() {
    BeeperApp app = (BeeperApp) getApplication();

    if (app.getPreferences().exportRunningSince() == 0L || (Calendar.getInstance().getTimeInMillis()
            - app.getPreferences().exportRunningSince()) >= 120000) { //2 min

        enableDisableView(findViewById(R.id.export_settings), true);

        CheckBox rawExp = (CheckBox) findViewById(R.id.export_raw);
        rawExp.setChecked(rawExport);//  w w w .j a v a 2 s .  c  om
        rawExp.setOnClickListener(this);

        CheckBox photoExp = (CheckBox) findViewById(R.id.export_photos);
        View photoExpGroup = findViewById(R.id.export_photos_group);

        if (PhotoUtils.isEnabled(ExportActivity.this)) {
            photoExp.setVisibility(View.VISIBLE);
            photoExpGroup.setVisibility(View.VISIBLE);

            File[] photos = PhotoUtils.getPhotos(ExportActivity.this);
            if (photos != null && photos.length > 0) {
                photoExp.setEnabled(true);
                photoExp.setChecked(photoExport);
                photoExp.setOnClickListener(this);

                enableDisableView(photoExpGroup, photoExport);
            } else {
                photoExp.setChecked(false);
                photoExp.setEnabled(false);
                enableDisableView(photoExpGroup, false);
            }

            downscalePhotos = (Spinner) findViewById(R.id.export_downscale_photos);
            downscaleAdapter = new ArrayAdapter<CharSequence>(ExportActivity.this,
                    android.R.layout.simple_spinner_item, new ArrayList<CharSequence>());
            downscaleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            downscalePhotos.setAdapter(downscaleAdapter);
            downscalePhotos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    densityItem = position;
                    Bundle opts = new Bundle();
                    opts.putBoolean("photoExport", photoExport);
                    opts.putBoolean("rawExport", rawExport);
                    estimatedSize.setText(String.format(getString(R.string.export_archive_estimated_size),
                            exporter.getReadableArchiveSize(opts,
                                    densityFactors.get(downscalePhotos.getSelectedItemPosition()).intValue())));
                }

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

                }
            });

            if (photoAvgSize == 0) {
                File[] photoFiles = PhotoUtils.getPhotos(ExportActivity.this);
                int count;
                int overallSize = 0;
                for (count = 0; count < photoFiles.length; count++) {
                    overallSize += photoFiles[count].length();
                }
                if (count > 0) {
                    photoAvgSize = overallSize / count;
                }
            }

            if (photoAvgDensity == 0) {
                new Thread(new PhotoDimRunnable(ExportActivity.this, new PhotoDimHandler(ExportActivity.this)))
                        .start();
            } else {
                TextView density = (TextView) findViewById(R.id.export_photos_avg_size);
                density.setText(
                        getString(R.string.export_photos_avg_size, String.format("%.1f", photoAvgDensity)));

                downscaleAdapter.add(String.format(getString(R.string.export_downscale_original_size),
                        DataExporter.getReadableFileSize(photoAvgSize, 0)));
                densityFactors.add(Integer.valueOf(1));
                int densityFactor = 2;

                for (; (Math.round((photoAvgDensity / densityFactor) * 2) / 2f) > 1; densityFactor *= 2) {
                    downscaleAdapter.add(String.format(getString(R.string.export_downscale),
                            String.format("%.1f", Math.round((photoAvgDensity / densityFactor) * 2) / 2f),
                            DataExporter.getReadableFileSize(photoAvgSize / densityFactor, 0)));
                    densityFactors.add(Integer.valueOf(densityFactor));
                }

                downscaleAdapter.add(String.format(getString(R.string.export_downscale), String.valueOf(1),
                        DataExporter.getReadableFileSize(photoAvgSize / densityFactor, 0)));
                densityFactors.add(Integer.valueOf(densityFactor));

                if (densityItem != -1) {
                    downscalePhotos.setSelection(densityItem);
                }
            }

        } else {
            photoExp.setVisibility(View.GONE);
            photoExpGroup.setVisibility(View.GONE);
        }

        postActions = (Spinner) findViewById(R.id.export_post_actions);
        ArrayAdapter<CharSequence> actionsAdapter = ArrayAdapter.createFromResource(this,
                R.array.post_export_actions, android.R.layout.simple_spinner_item);
        actionsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        postActions.setAdapter(actionsAdapter);

        if (postActionItem != -1) {
            postActions.setSelection(postActionItem);
        }

        estimatedSize = (TextView) findViewById(R.id.export_estimated_size);
        int densityFactor = 1;

        if (densityFactors.size() > 0 && downscalePhotos.getSelectedItemPosition() >= 0) {
            densityFactor = densityFactors.get(downscalePhotos.getSelectedItemPosition()).intValue();
        }

        Bundle opts = new Bundle();
        opts.putBoolean("photoExport", photoExport);
        opts.putBoolean("rawExport", rawExport);
        estimatedSize.setText(String.format(getString(R.string.export_archive_estimated_size),
                exporter.getReadableArchiveSize(opts, densityFactor)));

        Button start = (Button) findViewById(R.id.export_start_button);
        ProgressBar progress = (ProgressBar) findViewById(R.id.export_progress_bar);
        TextView runningText = (TextView) findViewById(R.id.export_running_text);

        start.setVisibility(View.VISIBLE);
        progress.setVisibility(View.GONE);
        runningText.setVisibility(View.GONE);
    } else {
        Button start = (Button) findViewById(R.id.export_start_button);
        ProgressBar progress = (ProgressBar) findViewById(R.id.export_progress_bar);
        TextView runningText = (TextView) findViewById(R.id.export_running_text);

        start.setVisibility(View.GONE);
        progress.setVisibility(View.VISIBLE);
        runningText.setVisibility(View.VISIBLE);

        enableDisableView(findViewById(R.id.export_settings), false);
    }
}

From source file:se.toxbee.sleepfighter.activity.EditGPSFilterAreaActivity.java

/**
 * Sets up the spinner for modes.//from   www  . j av  a 2 s .  co  m
 */
private void setupModeSpinner() {
    Spinner spinner = (Spinner) this.findViewById(R.id.action_edit_gpsfilter_area_mode);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.action_edit_gpsfilter_area_mode, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

    spinner.setSelection(this.area.getMode() == GPSFilterMode.INCLUDE ? 0 : 1);

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

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

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

@Override
protected void onCollectionLoaded(Collection col) {
    super.onCollectionLoaded(col);
    Timber.d("onCollectionLoaded()");
    mDeckNames = new HashMap<String, String>();
    for (long did : getCol().getDecks().allIds()) {
        mDeckNames.put(String.valueOf(did), getCol().getDecks().name(did));
    }/* w w w . java2 s  . c  o m*/
    registerExternalStorageListener();

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

    // Add drop-down menu to select deck to action bar.
    mDropDownDecks = getCol().getDecks().allSorted();
    mDropDownAdapter = new DeckDropDownAdapter(this, mDropDownDecks);
    mActionBar = getSupportActionBar();
    mActionBar.setDisplayShowTitleEnabled(false);
    mActionBarSpinner = (Spinner) findViewById(R.id.toolbar_spinner);
    mActionBarSpinner.setAdapter(mDropDownAdapter);
    mActionBarSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            selectDropDownItem(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    mActionBarSpinner.setVisibility(View.VISIBLE);

    try {
        mOrder = CARD_ORDER_NONE;
        String colOrder = getCol().getConf().getString("sortType");
        for (int c = 0; c < fSortTypes.length; ++c) {
            if (fSortTypes[c].equals(colOrder)) {
                mOrder = c;
                break;
            }
        }
        if (mOrder == 1 && preferences.getBoolean("cardBrowserNoSorting", false)) {
            mOrder = 0;
        }
        mOrderAsc = Upgrade.upgradeJSONIfNecessary(getCol(), getCol().getConf(), "sortBackwards", false);
        // default to descending for non-text fields
        if (fSortTypes[mOrder].equals("noteFld")) {
            mOrderAsc = !mOrderAsc;
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    mCards = new ArrayList<>();
    mCardsListView = (ListView) findViewById(R.id.card_browser_list);
    // Create a spinner for column1
    mCardsColumn1Spinner = (Spinner) findViewById(R.id.browser_column1_spinner);
    ArrayAdapter<CharSequence> column1Adapter = ArrayAdapter.createFromResource(this,
            R.array.browser_column1_headings, android.R.layout.simple_spinner_item);
    column1Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mCardsColumn1Spinner.setAdapter(column1Adapter);
    mColumn1Index = AnkiDroidApp.getSharedPrefs(getBaseContext()).getInt("cardBrowserColumn1", 0);
    mCardsColumn1Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // If a new column was selected then change the key used to map from mCards to the column TextView
            if (pos != mColumn1Index) {
                mColumn1Index = pos;
                AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).edit()
                        .putInt("cardBrowserColumn1", mColumn1Index).commit();
                String[] fromMap = mCardsAdapter.getFromMapping();
                fromMap[0] = COLUMN1_KEYS[mColumn1Index];
                mCardsAdapter.setFromMapping(fromMap);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Do Nothing
        }
    });
    // Load default value for column2 selection
    mColumn2Index = AnkiDroidApp.getSharedPrefs(getBaseContext()).getInt("cardBrowserColumn2", 0);
    // Setup the column 2 heading as a spinner so that users can easily change the column type
    mCardsColumn2Spinner = (Spinner) findViewById(R.id.browser_column2_spinner);
    ArrayAdapter<CharSequence> column2Adapter = ArrayAdapter.createFromResource(this,
            R.array.browser_column2_headings, android.R.layout.simple_spinner_item);
    column2Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mCardsColumn2Spinner.setAdapter(column2Adapter);
    // Create a new list adapter with updated column map any time the user changes the column
    mCardsColumn2Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // If a new column was selected then change the key used to map from mCards to the column TextView
            if (pos != mColumn2Index) {
                mColumn2Index = pos;
                AnkiDroidApp.getSharedPrefs(AnkiDroidApp.getInstance().getBaseContext()).edit()
                        .putInt("cardBrowserColumn2", mColumn2Index).commit();
                String[] fromMap = mCardsAdapter.getFromMapping();
                fromMap[1] = COLUMN2_KEYS[mColumn2Index];
                mCardsAdapter.setFromMapping(fromMap);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Do Nothing
        }
    });
    // get the font and font size from the preferences
    int sflRelativeFontSize = preferences.getInt("relativeCardBrowserFontSize", DEFAULT_FONT_SIZE_RATIO);
    String sflCustomFont = preferences.getString("browserEditorFont", "");
    // make a new list adapter mapping the data in mCards to column1 and column2 of R.layout.card_item_browser
    mCardsAdapter = new MultiColumnListAdapter(this, mCards, R.layout.card_item_browser,
            new String[] { COLUMN1_KEYS[mColumn1Index], COLUMN2_KEYS[mColumn2Index] },
            new int[] { R.id.card_sfld, R.id.card_column2 }, "flags", sflRelativeFontSize, sflCustomFont);
    // link the adapter to the main mCardsListView
    mCardsListView.setAdapter(mCardsAdapter);
    // make the second column load dynamically when scrolling
    mCardsListView.setOnScrollListener(new RenderOnScroll());
    // set the spinner index
    mCardsColumn1Spinner.setSelection(mColumn1Index);
    mCardsColumn2Spinner.setSelection(mColumn2Index);

    mCardsListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // load up the card selected on the list
            mPositionInCardsList = position;
            long cardId = Long.parseLong(mCards.get(mPositionInCardsList).get("id"));
            sCardBrowserCard = getCol().getCard(cardId);
            // start note editor using the card we just loaded
            Intent editCard = new Intent(CardBrowser.this, NoteEditor.class);
            editCard.putExtra(NoteEditor.EXTRA_CALLER, NoteEditor.CALLER_CARDBROWSER_EDIT);
            editCard.putExtra(NoteEditor.EXTRA_CARD_ID, sCardBrowserCard.getId());
            startActivityForResultWithAnimation(editCard, EDIT_CARD, ActivityTransitionAnimation.LEFT);
        }
    });
    mCardsListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
            mPositionInCardsList = position;
            HashMap<String, String> card = mCards.get(mPositionInCardsList);
            int flags = Integer.parseInt(card.get("flags"));
            String cardName = card.get("sfld");
            boolean isMarked = (flags == 2 || flags == 3);
            boolean isSuspended = (flags == 1 || flags == 3);
            showDialogFragment(
                    CardBrowserContextMenu.newInstance(cardName, isMarked, isSuspended, mContextMenuListener));
            return true;
        }
    });

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    // initialize mSearchTerms to a default value
    mSearchTerms = "";

    // set the currently selected deck
    if (sLastSelectedDeckIndex == -1) {
        String currentDeckName;
        try {
            currentDeckName = getCol().getDecks().current().getString("name");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        for (int dropDownDeckIdx = 0; dropDownDeckIdx < mDropDownDecks.size(); dropDownDeckIdx++) {
            JSONObject deck = mDropDownDecks.get(dropDownDeckIdx);
            String deckName;
            try {
                deckName = deck.getString("name");
            } catch (JSONException e) {
                throw new RuntimeException();
            }
            if (deckName.equals(currentDeckName)) {
                selectDropDownItem(dropDownDeckIdx + 1);
                break;
            }
        }
    } else if (sLastSelectedDeckIndex > 0 && sLastSelectedDeckIndex < mDropDownDecks.size()) {
        selectDropDownItem(sLastSelectedDeckIndex);
    }
}

From source file:website.openeng.anki.CardBrowser.java

@Override
protected void onCollectionLoaded(Collection col) {
    super.onCollectionLoaded(col);
    Timber.d("onCollectionLoaded()");
    mDeckNames = new HashMap<String, String>();
    for (long did : getCol().getDecks().allIds()) {
        mDeckNames.put(String.valueOf(did), getCol().getDecks().name(did));
    }/*from   www . j  ava2 s.c o  m*/
    registerExternalStorageListener();

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

    // Add drop-down menu to select deck to action bar.
    mDropDownDecks = getCol().getDecks().allSorted();
    mDropDownAdapter = new DeckDropDownAdapter(this, mDropDownDecks);
    mActionBar = getSupportActionBar();
    mActionBar.setDisplayShowTitleEnabled(false);
    mActionBarSpinner = (Spinner) findViewById(R.id.toolbar_spinner);
    mActionBarSpinner.setAdapter(mDropDownAdapter);
    mActionBarSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            selectDropDownItem(position);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // do nothing
        }
    });
    mActionBarSpinner.setVisibility(View.VISIBLE);

    try {
        mOrder = CARD_ORDER_NONE;
        String colOrder = getCol().getConf().getString("sortType");
        for (int c = 0; c < fSortTypes.length; ++c) {
            if (fSortTypes[c].equals(colOrder)) {
                mOrder = c;
                break;
            }
        }
        if (mOrder == 1 && preferences.getBoolean("cardBrowserNoSorting", false)) {
            mOrder = 0;
        }
        mOrderAsc = Upgrade.upgradeJSONIfNecessary(getCol(), getCol().getConf(), "sortBackwards", false);
        // default to descending for non-text fields
        if (fSortTypes[mOrder].equals("noteFld")) {
            mOrderAsc = !mOrderAsc;
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }

    mCards = new ArrayList<HashMap<String, String>>();
    mCardsListView = (ListView) findViewById(R.id.card_browser_list);
    // Create a spinner for column1, but without letting the user change column
    // TODO: Maybe allow column1 to be changed as well, but always make default sfld
    mCardsColumn1Spinner = (Spinner) findViewById(R.id.browser_column1_spinner);
    ArrayAdapter<CharSequence> column1Adapter = ArrayAdapter.createFromResource(this,
            R.array.browser_column1_headings, android.R.layout.simple_spinner_item);
    column1Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mCardsColumn1Spinner.setAdapter(column1Adapter);
    mCardsColumn1Spinner.setClickable(false); // We disable and set plain background since it only has 1 item
    // Load default value for column2 selection
    mColumn2Index = KanjiDroidApp.getSharedPrefs(getBaseContext()).getInt("cardBrowserColumn2", 0);
    // Setup the column 2 heading as a spinner so that users can easily change the column type
    mCardsColumn2Spinner = (Spinner) findViewById(R.id.browser_column2_spinner);
    ArrayAdapter<CharSequence> column2Adapter = ArrayAdapter.createFromResource(this,
            R.array.browser_column2_headings, android.R.layout.simple_spinner_item);
    column2Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mCardsColumn2Spinner.setAdapter(column2Adapter);
    // Create a new list adapter with updated column map any time the user changes the column
    mCardsColumn2Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            // If a new column was selected then change the key used to map from mCards to the column TextView
            if (pos != mColumn2Index) {
                mColumn2Index = pos;
                KanjiDroidApp.getSharedPrefs(KanjiDroidApp.getInstance().getBaseContext()).edit()
                        .putInt("cardBrowserColumn2", mColumn2Index).commit();
                String[] fromMap = mCardsAdapter.getFromMapping();
                fromMap[1] = COLUMN_KEYS[mColumn2Index];
                mCardsAdapter.setFromMapping(fromMap);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Do Nothing
        }
    });
    // get the font and font size from the preferences
    int sflRelativeFontSize = preferences.getInt("relativeCardBrowserFontSize", DEFAULT_FONT_SIZE_RATIO);
    String sflCustomFont = preferences.getString("browserEditorFont", "");
    // make a new list adapter mapping the data in mCards to column1 and column2 of R.layout.card_item_browser
    mCardsAdapter = new MultiColumnListAdapter(this, mCards, R.layout.card_item_browser,
            new String[] { "sfld", COLUMN_KEYS[mColumn2Index] },
            new int[] { R.id.card_sfld, R.id.card_column2 }, "flags", sflRelativeFontSize, sflCustomFont);
    // link the adapter to the main mCardsListView
    mCardsListView.setAdapter(mCardsAdapter);
    // make the second column load dynamically when scrolling
    mCardsListView.setOnScrollListener(new RenderOnScroll());
    // set the spinner index
    mCardsColumn2Spinner.setSelection(mColumn2Index);

    mCardsListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // load up the card selected on the list
            mPositionInCardsList = position;
            long cardId = Long.parseLong(mCards.get(mPositionInCardsList).get("id"));
            sCardBrowserCard = getCol().getCard(cardId);
            // start note editor using the card we just loaded
            Intent editCard = new Intent(CardBrowser.this, NoteEditor.class);
            editCard.putExtra(NoteEditor.EXTRA_CALLER, NoteEditor.CALLER_CARDBROWSER_EDIT);
            editCard.putExtra(NoteEditor.EXTRA_CARD_ID, sCardBrowserCard.getId());
            startActivityForResultWithAnimation(editCard, EDIT_CARD, ActivityTransitionAnimation.LEFT);
        }
    });
    mCardsListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
            mPositionInCardsList = position;
            HashMap<String, String> card = mCards.get(mPositionInCardsList);
            int flags = Integer.parseInt(card.get("flags"));
            String cardName = card.get("sfld");
            boolean isMarked = (flags == 2 || flags == 3);
            boolean isSuspended = (flags == 1 || flags == 3);
            showDialogFragment(
                    CardBrowserContextMenu.newInstance(cardName, isMarked, isSuspended, mContextMenuListener));
            return true;
        }
    });

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    // initialize mSearchTerms to a default value
    mSearchTerms = "";

    // set the currently selected deck
    if (!sIsWholeCollection) {
        String currentDeckName;
        try {
            currentDeckName = getCol().getDecks().current().getString("name");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        for (int dropDownDeckIdx = 0; dropDownDeckIdx < mDropDownDecks.size(); dropDownDeckIdx++) {
            JSONObject deck = mDropDownDecks.get(dropDownDeckIdx);
            String deckName;
            try {
                deckName = deck.getString("name");
            } catch (JSONException e) {
                throw new RuntimeException();
            }
            if (deckName.equals(currentDeckName)) {
                selectDropDownItem(dropDownDeckIdx + 1);
                break;
            }
        }
    }
    hideProgressBar();
}