Example usage for android.widget Switch setChecked

List of usage examples for android.widget Switch setChecked

Introduction

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

Prototype

@Override
    public void setChecked(boolean checked) 

Source Link

Usage

From source file:apps.junkuvo.alertapptowalksafely.MainActivity.java

public void setSwitchInLayout(View layout) {
    final RadioButton radioButtonTop = (RadioButton) layout.findViewById(R.id.radiobutton_top);
    final RadioButton radioButtonCenter = (RadioButton) layout.findViewById(R.id.radiobutton_center);
    final RadioButton radioButtonBottom = (RadioButton) layout.findViewById(R.id.radiobutton_bottom);
    Switch swh = (Switch) layout.findViewById(R.id.swhToastOnOff);
    swh.setChecked(mIsToastOn);
    swh.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mIsToastOn = isChecked;//w ww  .ja  va  2 s  .c  o  m
            if (mAlertService != null && mAlertService.isBoundService()) {
                mAlertService.setIsToastOn(mIsToastOn);
            }
            radioButtonBottom.setEnabled(isChecked);
            radioButtonTop.setEnabled(isChecked);
            radioButtonCenter.setEnabled(isChecked);
        }
    });
    swh = (Switch) layout.findViewById(R.id.swhVibrationOnOff);
    swh.setChecked(mIsVibrationOn);
    swh.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mIsVibrationOn = isChecked;
            if (mAlertService != null && mAlertService.isBoundService()) {
                mAlertService.setIsVibrationOn(mIsVibrationOn);
            }
        }
    });
    swh = (Switch) layout.findViewById(R.id.swhPasscodeOnOff);
    swh.setChecked(mPasscodeOn);
    swh.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mPasscodeOn = isChecked;
        }
    });

    if (mAlertService != null) {
        swh.setEnabled(!mAlertService.IsRunningAlertService());
    } else {
        swh.setEnabled(true);
    }
}

From source file:de.bogutzky.psychophysiocollector.app.MainActivity.java

private void showSettings() {
    final SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
    int selfReportIntervalSpinnerPosition = sharedPref.getInt("selfReportIntervalSpinnerPosition", 2);
    int selfReportVarianceSpinnerPosition = sharedPref.getInt("selfReportVarianceSpinnerPosition", 0);
    int questionnaireSpinnerPosition = sharedPref.getInt("questionnaireSpinnerPosition", 0);
    //int baselineQuestionnaireSpinnerPosition = sharedPref.getInt("baselineQuestionnaireSpinnerPosition", 0);
    String activityName = sharedPref.getString("activityName", "");
    String participantFirstName = sharedPref.getString("participantFirstName", "");
    String participantLastName = sharedPref.getString("participantLastName", "");
    boolean configureInterval = sharedPref.getBoolean("configureInterval", false);
    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.settings);
    dialog.setTitle(getString(R.string.action_settings));
    dialog.setCancelable(true);//from w  ww  . j  av  a 2 s .c o m
    WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
    lp.copyFrom(dialog.getWindow().getAttributes());
    lp.width = WindowManager.LayoutParams.MATCH_PARENT;
    lp.height = WindowManager.LayoutParams.MATCH_PARENT;
    dialog.getWindow().setAttributes(lp);
    selfReportIntervalSpinner = (Spinner) dialog.findViewById(R.id.self_report_interval_spinner);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.study_protocol_settings_self_report_interval_values, android.R.layout.simple_spinner_item);
    selfReportIntervalSpinner.setAdapter(adapter);
    selfReportIntervalSpinner.setSelection(selfReportIntervalSpinnerPosition);
    selfReportVarianceSpinner = (Spinner) dialog.findViewById(R.id.self_report_variance_spinner);
    ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(this,
            R.array.study_protocol_settings_self_report_variance_values, android.R.layout.simple_spinner_item);
    selfReportVarianceSpinner.setAdapter(adapter2);
    selfReportVarianceSpinner.setSelection(selfReportVarianceSpinnerPosition);

    questionnaireSpinner = (Spinner) dialog.findViewById(R.id.questionnaireSpinner);
    //baselineQuestionnaireSpinner = (Spinner) dialog.findViewById(R.id.baseline_questionnaireSpinner);

    String[] questionnaireTitles = new String[0];
    try {
        questionnaireTitles = new String[questionnaireCount];
        for (int i = 0; i < questionnaireCount; i++) {
            String questionnaireFilename = questionnaireFilenames[i];
            String questionnairePath = "questionnaires/" + localeString + "/" + questionnaireFilename;
            try {
                JSONObject questionnaire = Utils
                        .getJSONObjectFromInputStream(getAssets().open(questionnairePath));
                String questionnaireTitle = questionnaire.getJSONObject("questionnaire").getString("title");
                questionnaireTitles[i] = questionnaireTitle;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    ArrayAdapter<String> qSpinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item,
            questionnaireTitles);
    questionnaireSpinner.setAdapter(qSpinnerAdapter);
    questionnaireSpinner.setSelection(questionnaireSpinnerPosition);
    //baselineQuestionnaireSpinner.setAdapter(qSpinnerAdapter);
    //baselineQuestionnaireSpinner.setSelection(baselineQuestionnaireSpinnerPosition);

    final EditText participantFirstNameEditText = (EditText) dialog
            .findViewById(R.id.participant_first_name_edit_text);
    final EditText participantLastNameEditText = (EditText) dialog
            .findViewById(R.id.participant_last_name_edit_text);
    final EditText activityNameEditText = (EditText) dialog.findViewById(R.id.activity_name_edit_text);
    participantFirstNameEditText.setText(participantFirstName);
    participantLastNameEditText.setText(participantLastName);
    activityNameEditText.setText(activityName);

    final Switch configureIntervalSwitch = (Switch) dialog.findViewById(R.id.configure_interval_switch);
    configureIntervalSwitch.setChecked(configureInterval);
    if (configureInterval) {
        dialog.findViewById(R.id.configure_interval_layout).setVisibility(View.VISIBLE);
        dialog.findViewById(R.id.configure_variance_layout).setVisibility(View.VISIBLE);
    } else {
        dialog.findViewById(R.id.configure_interval_layout).setVisibility(View.GONE);
        dialog.findViewById(R.id.configure_variance_layout).setVisibility(View.GONE);
    }

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

        @Override
        public void onClick(View view) {
            selfReportInterval = Integer.valueOf(selfReportIntervalSpinner.getSelectedItem().toString());
            selfReportVariance = Integer.valueOf(selfReportVarianceSpinner.getSelectedItem().toString());

            MainActivity.this.participantFirstName = participantFirstNameEditText.getText().toString().trim();
            MainActivity.this.participantLastName = participantLastNameEditText.getText().toString().trim();
            MainActivity.this.activityName = activityNameEditText.getText().toString().trim();
            MainActivity.this.intervalConfigured = configureIntervalSwitch.isChecked();

            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putInt("selfReportIntervalSpinnerPosition",
                    selfReportIntervalSpinner.getSelectedItemPosition());
            editor.putInt("selfReportVarianceSpinnerPosition",
                    selfReportVarianceSpinner.getSelectedItemPosition());
            editor.putInt("questionnaireSpinnerPosition", questionnaireSpinner.getSelectedItemPosition());
            //editor.putInt("baselineQuestionnaireSpinnerPosition", baselineQuestionnaireSpinner.getSelectedItemPosition());
            editor.putInt("selfReportInterval",
                    Integer.valueOf(selfReportIntervalSpinner.getSelectedItem().toString()));
            editor.putInt("selfReportVariance",
                    Integer.valueOf(selfReportVarianceSpinner.getSelectedItem().toString()));

            editor.putString("participantFirstName", participantFirstNameEditText.getText().toString().trim());
            editor.putString("participantLastName", participantLastNameEditText.getText().toString().trim());
            editor.putString("activityName", activityNameEditText.getText().toString().trim());
            editor.putBoolean("configureInterval", configureIntervalSwitch.isChecked());
            editor.apply();

            dialog.dismiss();
        }
    });

    configureIntervalSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                dialog.findViewById(R.id.configure_interval_layout).setVisibility(View.VISIBLE);
                dialog.findViewById(R.id.configure_variance_layout).setVisibility(View.VISIBLE);
            } else {
                dialog.findViewById(R.id.configure_interval_layout).setVisibility(View.GONE);
                dialog.findViewById(R.id.configure_variance_layout).setVisibility(View.GONE);
            }
        }
    });
    dialog.show();
}

From source file:it.iziozi.iziozi.gui.IOBoardActivity.java

public void tapOnSpeakableButton(final IOSpeakableImageButton spkBtn, final Integer level) {
    if (IOGlobalConfiguration.isEditing) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();

        View layoutView = inflater.inflate(R.layout.editmode_alertview, null);

        builder.setTitle(getString(R.string.choose));

        builder.setView(layoutView);// w w w .j  a v  a 2 s.c  o m

        final AlertDialog dialog = builder.create();

        final Switch matrioskaSwitch = (Switch) layoutView.findViewById(R.id.editModeAlertToggleBoard);
        Button editPictoButton = (Button) layoutView.findViewById(R.id.editModeAlertActionPicture);
        final Button editBoardButton = (Button) layoutView.findViewById(R.id.editModeAlertActionBoard);

        matrioskaSwitch.setChecked(spkBtn.getIsMatrioska());
        editBoardButton.setEnabled(spkBtn.getIsMatrioska());

        matrioskaSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                spkBtn.setIsMatrioska(isChecked);
                editBoardButton.setEnabled(isChecked);
            }
        });

        editPictoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //spkBtn.showInsertDialog();
                Intent cIntent = new Intent(getApplicationContext(), IOCreateButtonActivity.class);
                cIntent.putExtra(BUTTON_INDEX,
                        mActualLevel.getBoardAtIndex(mActualIndex).getButtons().indexOf(spkBtn));

                cIntent.putExtra(BUTTON_TEXT, spkBtn.getSentence());
                cIntent.putExtra(BUTTON_TITLE, spkBtn.getmTitle());
                cIntent.putExtra(BUTTON_IMAGE_FILE, spkBtn.getmImageFile());
                cIntent.putExtra(BUTTON_AUDIO_FILE, spkBtn.getAudioFile());

                startActivityForResult(cIntent, CREATE_BUTTON_CODE);

                matrioskaSwitch.setOnCheckedChangeListener(null);

                dialog.dismiss();
            }
        });

        editBoardButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                IOLevel nestedBoard = spkBtn.getLevel();

                pushLevel(nestedBoard);

                matrioskaSwitch.setOnCheckedChangeListener(null);

                dialog.dismiss();
            }
        });

        dialog.show();

    } else {

        if (IOGlobalConfiguration.isScanMode) {
            IOSpeakableImageButton scannedButton = mActualLevel.getBoardAtIndex(mActualIndex).getButtons()
                    .get(mActualScanIndex);
            if (scannedButton.getAudioFile() != null && scannedButton.getAudioFile().length() > 0) {

                final MediaPlayer mPlayer = new MediaPlayer();
                try {
                    mPlayer.setDataSource(scannedButton.getAudioFile());
                    mPlayer.prepare();

                    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mPlayer.release();

                        }
                    });

                    mPlayer.start();

                } catch (IOException e) {
                    Log.e("playback_debug", "prepare() failed");
                }
            } else if (mCanSpeak) {
                Log.d("speakable_debug", "should say: " + scannedButton.getSentence());
                if (scannedButton.getSentence() == "")
                    tts.speak(getResources().getString(R.string.tts_nosentence), TextToSpeech.QUEUE_FLUSH,
                            null);
                else
                    tts.speak(scannedButton.getSentence(), TextToSpeech.QUEUE_FLUSH, null);
            } else {
                Toast.makeText(this, getResources().getString(R.string.tts_notinitialized), Toast.LENGTH_LONG)
                        .show();
            }

            if (scannedButton.getIsMatrioska() && null != scannedButton.getLevel()) {
                pushLevel(scannedButton.getLevel());
            }
        } else {

            if (spkBtn.getAudioFile() != null && spkBtn.getAudioFile().length() > 0) {

                final MediaPlayer mPlayer = new MediaPlayer();
                try {
                    mPlayer.setDataSource(spkBtn.getAudioFile());
                    mPlayer.prepare();

                    mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            mPlayer.release();

                        }
                    });

                    mPlayer.start();

                } catch (IOException e) {
                    Log.e("playback_debug", "prepare() failed");
                }
            } else if (mCanSpeak) {
                Log.d("speakable_debug", "should say: " + spkBtn.getSentence());
                if (spkBtn.getSentence() == "")
                    tts.speak(getResources().getString(R.string.tts_nosentence), TextToSpeech.QUEUE_FLUSH,
                            null);
                else
                    tts.speak(spkBtn.getSentence(), TextToSpeech.QUEUE_FLUSH, null);
            } else {
                Toast.makeText(this, getResources().getString(R.string.tts_notinitialized), Toast.LENGTH_LONG)
                        .show();
            }

            if (spkBtn.getIsMatrioska() && null != spkBtn.getLevel()) {
                pushLevel(spkBtn.getLevel());
            }
        }
    }
}

From source file:com.coinblesk.client.MainActivity.java

private void initSwitch(Menu menu) {
    MenuItem item = menu.findItem(R.id.myswitch);
    View view = item.getActionView();
    final Switch mySwitch = (Switch) view.findViewById(R.id.switchAB);
    final AtomicReference<CountDownTimer> ref = new AtomicReference<>();
    mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override//from   www . j  av a 2  s .c o m
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if (isChecked) {
                //enable BT
                ref.set(new CountDownTimer(30000, 1000) {
                    int i = 0;

                    public void onTick(final long millisUntilFinished) {
                        mySwitch.setButtonDrawable(
                                (i++ % 2) == 0 ? R.drawable.bluetooth_onon : R.drawable.bluetooth_on);
                        mySwitch.setTextOn("" + millisUntilFinished / 1000);
                    }

                    public void onFinish() {
                        mySwitch.setButtonDrawable(R.drawable.bluetooth_on);
                        mySwitch.setChecked(false);
                    }

                });
                ref.get().start();
                LocalBroadcastManager.getInstance(MainActivity.this)
                        .sendBroadcast(new Intent(Constants.START_CLIENTS_ACTION));

            } else {
                //mySwitch.setShowText(false);
                CountDownTimer tmp;
                if ((tmp = ref.getAndSet(null)) != null) {
                    tmp.cancel();
                }
                LocalBroadcastManager.getInstance(MainActivity.this)
                        .sendBroadcast(new Intent(Constants.STOP_CLIENTS_ACTION));
            }
        }
    });
}

From source file:com.npi.muzeiflickr.ui.activities.SettingsActivity.java

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

    setContentView(R.layout.settings_activity);

    final SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    final SharedPreferences.Editor editor = settings.edit();

    //Find views//from www. ja  v a 2  s .c o m

    Switch wifiOnly = (Switch) findViewById(R.id.wifi_only);
    mRefreshRate = (TextView) findViewById(R.id.refresh_rate);
    ImageView aboutShortcut = (ImageView) findViewById(R.id.about);
    mRequestList = (DragSortListView) findViewById(R.id.content_list);
    mUndoContainer = (RelativeLayout) findViewById(R.id.undo_container);
    mLastDeletedItemText = (TextView) findViewById(R.id.last_deleted_item);
    TextView mLastDeletedUndo = (TextView) findViewById(R.id.last_deleted_undo);

    List<RequestData> items = new ArrayList<RequestData>();
    items.addAll(Search.listAll(Search.class));
    items.addAll(User.listAll(User.class));
    items.addAll(Tag.listAll(Tag.class));
    items.addAll(FGroup.listAll(FGroup.class));

    mRequestAdapter = new RequestAdapter(this, items);

    final View footerView = getLayoutInflater().inflate(R.layout.list_footer, null);
    mRequestList.addFooterView(footerView);

    mRequestList.setAdapter(mRequestAdapter);

    mRequestList.setRemoveListener(onRemove);

    populateFooter(footerView);

    //Wifi status and setting
    wifiOnly.setChecked(settings.getBoolean(PreferenceKeys.WIFI_ONLY, false));

    wifiOnly.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            editor.putBoolean(PreferenceKeys.WIFI_ONLY, isChecked);
            editor.commit();
        }
    });

    //Other settings population
    int refreshRate = settings.getInt(PreferenceKeys.REFRESH_TIME, FlickrSource.DEFAULT_REFRESH_TIME);

    mRefreshRate.setText(Utils.convertDurationtoString(refreshRate));
    mRefreshRate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            HHmsPickerBuilder hpb = new HHmsPickerBuilder().setFragmentManager(getSupportFragmentManager())
                    .setStyleResId(R.style.MyCustomBetterPickerTheme);
            hpb.show();
        }
    });

    aboutShortcut.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AboutActivity.launchActivity(SettingsActivity.this);
        }
    });

    mLastDeletedUndo.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mLastDeletedItem instanceof User) {
                User user = ((User) mLastDeletedItem);
                user.setId(null);
                user.save();
            } else if (mLastDeletedItem instanceof Search) {
                Search search = ((Search) mLastDeletedItem);
                search.setId(null);
                search.save();
            }
            mRequestAdapter.add(mLastDeletedItem);
            mRequestAdapter.notifyDataSetChanged();
            mUndoContainer.setVisibility(View.GONE);
        }
    });

}

From source file:com.abhijitvalluri.android.fitnotifications.AppSettingsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_app_settings);

    Switch discardEmptySwitch;
    Switch allDaySwitch;/*  ww w.j a  v  a 2  s .co  m*/

    mFilterText = (EditText) findViewById(R.id.filter_text);
    mStartTimeButton = (Button) findViewById(R.id.start_time);
    mStopTimeButton = (Button) findViewById(R.id.stop_time);
    mNextDay = (TextView) findViewById(R.id.next_day);
    discardEmptySwitch = (Switch) findViewById(R.id.discard_empty);
    allDaySwitch = (Switch) findViewById(R.id.all_day);

    mFilterText.setHorizontallyScrolling(false);
    mFilterText.setMaxLines(5);

    if (savedInstanceState == null) {
        mAppSelection = getIntent().getParcelableExtra(APP_SELECTION_EXTRA);
        mStartTimeHour = mAppSelection.getStartTimeHour();
        mStartTimeMinute = mAppSelection.getStartTimeMinute();
        mStopTimeHour = mAppSelection.getStopTimeHour();
        mStopTimeMinute = mAppSelection.getStopTimeMinute();
        mDiscardEmptyNotifications = mAppSelection.isDiscardEmptyNotifications();
        mAllDaySchedule = mAppSelection.isAllDaySchedule();
    } else {
        mAppSelection = savedInstanceState.getParcelable(STATE_APP_SELECTION);
        mStartTimeHour = savedInstanceState.getInt(STATE_START_TIME_HOUR);
        mStartTimeMinute = savedInstanceState.getInt(STATE_START_TIME_MINUTE);
        mStopTimeHour = savedInstanceState.getInt(STATE_STOP_TIME_HOUR);
        mStopTimeMinute = savedInstanceState.getInt(STATE_STOP_TIME_MINUTE);
        mDiscardEmptyNotifications = savedInstanceState.getBoolean(STATE_DISCARD_EMPTY_NOTIFICATIONS);
        mAllDaySchedule = savedInstanceState.getBoolean(STATE_ALL_DAY_SCHEDULE);
    }

    discardEmptySwitch.setChecked(mDiscardEmptyNotifications);
    setTitle(mAppSelection.getAppName());
    mFilterText.setText(mAppSelection.getFilterText());

    allDaySwitch.setChecked(mAllDaySchedule);
    setupScheduleSettings();

    discardEmptySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mDiscardEmptyNotifications = isChecked;
        }
    });

    mStartTimeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getSupportFragmentManager();
            TimePickerFragment dialog = TimePickerFragment.newInstance(mStartTimeHour, mStartTimeMinute,
                    mStopTimeHour, mStopTimeMinute, START_TIME_REQUEST);
            dialog.show(manager, DIALOG_TIME);
        }
    });

    mStopTimeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager manager = getSupportFragmentManager();
            TimePickerFragment dialog = TimePickerFragment.newInstance(mStopTimeHour, mStopTimeMinute,
                    mStartTimeHour, mStartTimeMinute, STOP_TIME_REQUEST);
            dialog.show(manager, DIALOG_TIME);
        }
    });

    allDaySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mAllDaySchedule = isChecked;
            setupScheduleSettings();
        }
    });
}

From source file:de.baumann.browser.Browser_right.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*w  w w.j  av  a2s.c  o  m*/
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_search) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.showKeyboard(Browser_right.this, editText, 3, "", getString(R.string.app_search_hint));
    }

    if (id == R.id.action_history) {
        helper_main.switchToActivity(Browser_right.this, Popup_history.class, "", false);
    }

    if (id == R.id.action_search_chooseWebsite) {
        helper_editText.editText_searchWeb(editText, Browser_right.this);
    }

    if (id == R.id.action_pass) {
        helper_main.switchToActivity(Browser_right.this, Popup_pass.class, "", false);
        sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
        sharedPref.edit().putString("pass_copy_title", mWebView.getTitle()).apply();
    }

    if (id == R.id.action_toggle) {

        sharedPref.edit().putString("started", "yes").apply();

        if (Uri.parse(mWebView.getUrl()).getHost().length() == 0) {
            domain = getString(R.string.app_domain);
        } else {
            domain = Uri.parse(mWebView.getUrl()).getHost();
        }

        final String whiteList = sharedPref.getString("whiteList", "");

        AlertDialog.Builder builder = new AlertDialog.Builder(Browser_right.this);
        View dialogView = View.inflate(Browser_right.this, R.layout.dialog_toggle, null);

        Switch sw_java = (Switch) dialogView.findViewById(R.id.switch1);
        Switch sw_pictures = (Switch) dialogView.findViewById(R.id.switch2);
        Switch sw_location = (Switch) dialogView.findViewById(R.id.switch3);
        Switch sw_cookies = (Switch) dialogView.findViewById(R.id.switch4);
        final ImageButton whiteList_js = (ImageButton) dialogView.findViewById(R.id.imageButton_js);

        if (whiteList.contains(domain)) {
            whiteList_js.setImageResource(R.drawable.check_green);
        } else {
            whiteList_js.setImageResource(R.drawable.close_red);
        }
        if (sharedPref.getString("java_string", "True").equals(getString(R.string.app_yes))) {
            sw_java.setChecked(true);
        } else {
            sw_java.setChecked(false);
        }
        if (sharedPref.getString("pictures_string", "True").equals(getString(R.string.app_yes))) {
            sw_pictures.setChecked(true);
        } else {
            sw_pictures.setChecked(false);
        }
        if (sharedPref.getString("loc_string", "True").equals(getString(R.string.app_yes))) {
            sw_location.setChecked(true);
        } else {
            sw_location.setChecked(false);
        }
        if (sharedPref.getString("cookie_string", "True").equals(getString(R.string.app_yes))) {
            sw_cookies.setChecked(true);
        } else {
            sw_cookies.setChecked(false);
        }

        whiteList_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (whiteList.contains(domain)) {
                    whiteList_js.setImageResource(R.drawable.close_red);
                    String removed = whiteList.replaceAll(domain, "");
                    sharedPref.edit().putString("whiteList", removed).apply();
                } else {
                    whiteList_js.setImageResource(R.drawable.check_green);
                    sharedPref.edit().putString("whiteList", whiteList + " " + domain).apply();
                }
            }
        });
        sw_java.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("java_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(true);
                } else {
                    sharedPref.edit().putString("java_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(false);
                }

            }
        });
        sw_pictures.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                } else {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(false);
                }

            }
        });
        sw_location.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setGeolocationEnabled(true);
                    helper_main.grantPermissionsLoc(Browser_right.this);
                } else {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setGeolocationEnabled(false);
                }

            }
        });
        sw_cookies.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_yes)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                } else {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_no)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(false);
                }

            }
        });

        builder.setView(dialogView);
        builder.setTitle(R.string.menu_toggle_title);
        builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                mWebView.reload();
            }
        });
        builder.setNegativeButton(R.string.menu_settings, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
                sharedPref.edit().putString("lastActivity", "browser_right").apply();
                helper_main.switchToActivity(Browser_right.this, Activity_settings.class, "", true);
            }
        });

        final AlertDialog dialog = builder.create();
        // Display the custom alert dialog on interface
        dialog.show();

    }

    if (id == R.id.menu_save_screenshot) {
        screenshot();
    }

    if (id == R.id.menu_save_bookmark) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.editText_saveBookmark(editText, Browser_right.this, mWebView);
    }

    if (id == R.id.menu_save_readLater) {
        DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_right.this);
        db.open();
        if (db.isExist(mWebView.getUrl())) {
            Snackbar.make(editText, getString(R.string.toast_newTitle), Snackbar.LENGTH_LONG).show();
        } else {
            db.insert(helper_webView.getTitle(mWebView), mWebView.getUrl(), "", "", helper_main.createDate());
            Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG).show();
        }
    }

    if (id == R.id.menu_save_pass) {
        helper_editText.editText_savePass(Browser_right.this, mWebView, mWebView.getTitle(), mWebView.getUrl());
    }

    if (id == R.id.menu_createShortcut) {
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        i.setClassName(Browser_right.this, "de.baumann.browser.Browser_left");
        i.setData(Uri.parse(mWebView.getUrl()));

        Intent shortcut = new Intent();
        shortcut.putExtra("android.intent.extra.shortcut.INTENT", i);
        shortcut.putExtra("android.intent.extra.shortcut.NAME", "THE NAME OF SHORTCUT TO BE SHOWN");
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, mWebView.getTitle());
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                .fromContext(Browser_right.this.getApplicationContext(), R.mipmap.ic_launcher));
        shortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        Browser_right.this.sendBroadcast(shortcut);
        Snackbar.make(mWebView, R.string.menu_createShortcut_success, Snackbar.LENGTH_SHORT).show();
    }

    if (id == R.id.menu_share_screenshot) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("image/png");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
        Uri bmpUri = Uri.fromFile(shareFile);
        sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
        startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_screenshot))));
    }

    if (id == R.id.menu_share_link) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
        startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_link))));
    }

    if (id == R.id.menu_share_link_copy) {
        String url = mWebView.getUrl();
        ClipboardManager clipboard = (ClipboardManager) Browser_right.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
        Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT).show();
    }

    if (id == R.id.action_downloads) {
        helper_main.switchToActivity(Browser_right.this, Popup_files.class, "", false);
    }

    if (id == R.id.action_search_go) {

        String text = editText.getText().toString();
        helper_webView.openURL(Browser_right.this, mWebView, editText);
        helper_editText.hideKeyboard(Browser_right.this, editText, 0, text,
                getString(R.string.app_search_hint));
        helper_editText.editText_EditorAction(editText, Browser_right.this, mWebView, urlBar);
        urlBar.setVisibility(View.VISIBLE);
        editText.setVisibility(View.GONE);
    }

    if (id == R.id.action_search_onSite) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.showKeyboard(Browser_right.this, editText, 1, "", getString(R.string.app_search_hint));
        helper_editText.editText_FocusChange_searchSite(editText, Browser_right.this);
        helper_editText.editText_searchSite(editText, Browser_right.this, mWebView, urlBar);
    }

    if (id == R.id.action_search_onSite_go) {

        String text = editText.getText().toString();

        if (text.startsWith(getString(R.string.app_search))) {
            helper_editText.editText_searchSite(editText, Browser_right.this, mWebView, urlBar);
        } else {
            mWebView.findAllAsync(text);
            helper_editText.hideKeyboard(Browser_right.this, editText, 1,
                    getString(R.string.app_search) + " " + text, getString(R.string.app_search_hint_site));
        }
    }

    if (id == R.id.action_prev) {
        mWebView.findNext(false);
    }

    if (id == R.id.action_next) {
        mWebView.findNext(true);
    }

    if (id == R.id.action_cancel) {
        urlBar.setVisibility(View.VISIBLE);
        urlBar.setText(mWebView.getTitle());
        editText.setVisibility(View.GONE);
        helper_editText.editText_FocusChange(editText, Browser_right.this);
        helper_editText.editText_EditorAction(editText, Browser_right.this, mWebView, urlBar);
        helper_editText.hideKeyboard(Browser_right.this, editText, 0, mWebView.getTitle(),
                getString(R.string.app_search_hint));
    }

    if (id == R.id.action_save_bookmark) {
        helper_editText.editText_saveBookmark_save(editText, Browser_right.this, mWebView);
        urlBar.setVisibility(View.VISIBLE);
        editText.setVisibility(View.GONE);
    }

    return super.onOptionsItemSelected(item);
}

From source file:de.baumann.browser.Browser_left.java

@SuppressLint("SetJavaScriptEnabled")
@Override//from  ww w .  ja v a 2 s .c o  m
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_search) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.showKeyboard(Browser_left.this, editText, 3, "", getString(R.string.app_search_hint));
    }

    if (id == R.id.action_history) {
        helper_main.switchToActivity(Browser_left.this, Popup_history.class, "", false);
    }

    if (id == R.id.action_search_chooseWebsite) {
        helper_editText.editText_searchWeb(editText, Browser_left.this);
    }

    if (id == R.id.action_pass) {
        helper_main.switchToActivity(Browser_left.this, Popup_pass.class, "", false);
        sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
        sharedPref.edit().putString("pass_copy_title", mWebView.getTitle()).apply();
    }

    if (id == R.id.action_toggle) {

        sharedPref.edit().putString("started", "yes").apply();

        if (Uri.parse(mWebView.getUrl()).getHost().length() == 0) {
            domain = getString(R.string.app_domain);
        } else {
            domain = Uri.parse(mWebView.getUrl()).getHost();
        }

        final String whiteList = sharedPref.getString("whiteList", "");

        AlertDialog.Builder builder = new AlertDialog.Builder(Browser_left.this);
        View dialogView = View.inflate(Browser_left.this, R.layout.dialog_toggle, null);

        Switch sw_java = (Switch) dialogView.findViewById(R.id.switch1);
        Switch sw_pictures = (Switch) dialogView.findViewById(R.id.switch2);
        Switch sw_location = (Switch) dialogView.findViewById(R.id.switch3);
        Switch sw_cookies = (Switch) dialogView.findViewById(R.id.switch4);
        final ImageButton whiteList_js = (ImageButton) dialogView.findViewById(R.id.imageButton_js);

        if (whiteList.contains(domain)) {
            whiteList_js.setImageResource(R.drawable.check_green);
        } else {
            whiteList_js.setImageResource(R.drawable.close_red);
        }
        if (sharedPref.getString("java_string", "True").equals(getString(R.string.app_yes))) {
            sw_java.setChecked(true);
        } else {
            sw_java.setChecked(false);
        }
        if (sharedPref.getString("pictures_string", "True").equals(getString(R.string.app_yes))) {
            sw_pictures.setChecked(true);
        } else {
            sw_pictures.setChecked(false);
        }
        if (sharedPref.getString("loc_string", "True").equals(getString(R.string.app_yes))) {
            sw_location.setChecked(true);
        } else {
            sw_location.setChecked(false);
        }
        if (sharedPref.getString("cookie_string", "True").equals(getString(R.string.app_yes))) {
            sw_cookies.setChecked(true);
        } else {
            sw_cookies.setChecked(false);
        }

        whiteList_js.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (whiteList.contains(domain)) {
                    whiteList_js.setImageResource(R.drawable.close_red);
                    String removed = whiteList.replaceAll(domain, "");
                    sharedPref.edit().putString("whiteList", removed).apply();
                } else {
                    whiteList_js.setImageResource(R.drawable.check_green);
                    sharedPref.edit().putString("whiteList", whiteList + " " + domain).apply();
                }
            }
        });
        sw_java.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("java_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(true);
                } else {
                    sharedPref.edit().putString("java_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setJavaScriptEnabled(false);
                }

            }
        });
        sw_pictures.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(true);
                } else {
                    sharedPref.edit().putString("pictures_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setLoadsImagesAutomatically(false);
                }

            }
        });
        sw_location.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_yes)).apply();
                    mWebView.getSettings().setGeolocationEnabled(true);
                    helper_main.grantPermissionsLoc(Browser_left.this);
                } else {
                    sharedPref.edit().putString("loc_string", getString(R.string.app_no)).apply();
                    mWebView.getSettings().setGeolocationEnabled(false);
                }

            }
        });
        sw_cookies.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_yes)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                } else {
                    sharedPref.edit().putString("cookie_string", getString(R.string.app_no)).apply();
                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(false);
                }

            }
        });

        builder.setView(dialogView);
        builder.setTitle(R.string.menu_toggle_title);
        builder.setPositiveButton(R.string.toast_yes, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                mWebView.reload();
            }
        });
        builder.setNegativeButton(R.string.menu_settings, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int whichButton) {
                sharedPref.edit().putString("pass_copy_url", mWebView.getUrl()).apply();
                sharedPref.edit().putString("lastActivity", "browser_left").apply();
                helper_main.switchToActivity(Browser_left.this, Activity_settings.class, "", true);
            }
        });

        final AlertDialog dialog = builder.create();
        // Display the custom alert dialog on interface
        dialog.show();

    }

    if (id == R.id.menu_save_screenshot) {
        screenshot();
    }

    if (id == R.id.menu_save_bookmark) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.editText_saveBookmark(editText, Browser_left.this, mWebView);
    }

    if (id == R.id.menu_save_readLater) {
        DbAdapter_ReadLater db = new DbAdapter_ReadLater(Browser_left.this);
        db.open();
        if (db.isExist(mWebView.getUrl())) {
            Snackbar.make(editText, getString(R.string.toast_newTitle), Snackbar.LENGTH_LONG).show();
        } else {
            db.insert(helper_webView.getTitle(mWebView), mWebView.getUrl(), "", "", helper_main.createDate());
            Snackbar.make(mWebView, R.string.bookmark_added, Snackbar.LENGTH_LONG).show();
        }
    }

    if (id == R.id.menu_save_pass) {
        helper_editText.editText_savePass(Browser_left.this, mWebView, mWebView.getTitle(), mWebView.getUrl());
    }

    if (id == R.id.menu_createShortcut) {
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        i.setClassName(Browser_left.this, "de.baumann.browser.Browser_left");
        i.setData(Uri.parse(mWebView.getUrl()));

        Intent shortcut = new Intent();
        shortcut.putExtra("android.intent.extra.shortcut.INTENT", i);
        shortcut.putExtra("android.intent.extra.shortcut.NAME", "THE NAME OF SHORTCUT TO BE SHOWN");
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, mWebView.getTitle());
        shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource
                .fromContext(Browser_left.this.getApplicationContext(), R.mipmap.ic_launcher));
        shortcut.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
        Browser_left.this.sendBroadcast(shortcut);
        Snackbar.make(mWebView, R.string.menu_createShortcut_success, Snackbar.LENGTH_SHORT).show();
    }

    if (id == R.id.menu_share_screenshot) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("image/png");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
        Uri bmpUri = Uri.fromFile(shareFile);
        sharingIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
        startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_screenshot))));
    }

    if (id == R.id.menu_share_link) {
        Intent sharingIntent = new Intent(Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, mWebView.getTitle());
        sharingIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
        startActivity(Intent.createChooser(sharingIntent, (getString(R.string.app_share_link))));
    }

    if (id == R.id.menu_share_link_copy) {
        String url = mWebView.getUrl();
        ClipboardManager clipboard = (ClipboardManager) Browser_left.this
                .getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setPrimaryClip(ClipData.newPlainText("text", url));
        Snackbar.make(mWebView, R.string.context_linkCopy_toast, Snackbar.LENGTH_SHORT).show();
    }

    if (id == R.id.action_downloads) {
        helper_main.switchToActivity(Browser_left.this, Popup_files.class, "", false);
    }

    if (id == R.id.action_search_go) {

        String text = editText.getText().toString();
        helper_webView.openURL(Browser_left.this, mWebView, editText);
        helper_editText.hideKeyboard(Browser_left.this, editText, 0, text, getString(R.string.app_search_hint));
        helper_editText.editText_EditorAction(editText, Browser_left.this, mWebView, urlBar);
        urlBar.setVisibility(View.VISIBLE);
        editText.setVisibility(View.GONE);
    }

    if (id == R.id.action_search_onSite) {
        urlBar.setVisibility(View.GONE);
        editText.setVisibility(View.VISIBLE);
        helper_editText.showKeyboard(Browser_left.this, editText, 1, "", getString(R.string.app_search_hint));
        helper_editText.editText_FocusChange_searchSite(editText, Browser_left.this);
        helper_editText.editText_searchSite(editText, Browser_left.this, mWebView, urlBar);
    }

    if (id == R.id.action_search_onSite_go) {

        String text = editText.getText().toString();

        if (text.startsWith(getString(R.string.app_search))) {
            helper_editText.editText_searchSite(editText, Browser_left.this, mWebView, urlBar);
        } else {
            mWebView.findAllAsync(text);
            helper_editText.hideKeyboard(Browser_left.this, editText, 1,
                    getString(R.string.app_search) + " " + text, getString(R.string.app_search_hint_site));
        }
    }

    if (id == R.id.action_prev) {
        mWebView.findNext(false);
    }

    if (id == R.id.action_next) {
        mWebView.findNext(true);
    }

    if (id == R.id.action_cancel) {
        urlBar.setVisibility(View.VISIBLE);
        urlBar.setText(mWebView.getTitle());
        editText.setVisibility(View.GONE);
        helper_editText.editText_FocusChange(editText, Browser_left.this);
        helper_editText.editText_EditorAction(editText, Browser_left.this, mWebView, urlBar);
        helper_editText.hideKeyboard(Browser_left.this, editText, 0, mWebView.getTitle(),
                getString(R.string.app_search_hint));
    }

    if (id == R.id.action_save_bookmark) {
        helper_editText.editText_saveBookmark_save(editText, Browser_left.this, mWebView);
        urlBar.setVisibility(View.VISIBLE);
        editText.setVisibility(View.GONE);
    }

    return super.onOptionsItemSelected(item);
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //noinspection ConstantConditions
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.ic_tools_cpu_control));
    setContentView(R.layout.card_cpu_control);
    bootPrefs = getSharedPreferences("BOOT_PREFS", 0);

    graph = (LineGraph) findViewById(R.id.graph);
    line = new Line();
    LinePoint point = new LinePoint();
    point.setX(currX);// www  .j av a2s . c om
    point.setY(1);
    line.addPoint(point);
    line.setColor(Color.parseColor("#FFBB33"));
    graph.addLine(line);
    graph.setLineToFill(0);

    availableFrequencies = new String[0];
    String availableFrequenciesLine;

    mCoresOnline = (TextView) findViewById(R.id.cores_online);
    mGeneralGovernor = (Spinner) findViewById(R.id.general_governor);
    mGovernor = (Spinner) findViewById(R.id.governor);
    mGovernor2 = (Spinner) findViewById(R.id.governor2);
    mGovernor3 = (Spinner) findViewById(R.id.governor3);
    mGovernor4 = (Spinner) findViewById(R.id.governor4);

    Button customizeGov = (Button) findViewById(R.id.governor_customize_btn);
    customizeGov.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentManager fm = getSupportFragmentManager();
            GovernorDialog editNameDialog = new GovernorDialog();
            editNameDialog.show(fm, "governor_fragment");
        }
    });

    if (Helpers.doesFileExist(STEPS)) {
        availableFrequenciesLine = CPUHelper.readOneLineNotRoot(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));
                }
            });
        }
    }

    Switch snakeCharmer = (Switch) findViewById(R.id.snake_charmer_switch);
    if (!Helpers.doesFileExist(SNAKE_CHARMER_MAX_FREQ)) {
        LinearLayout cardSnakeCharmer = (LinearLayout) findViewById(R.id.card_snake_charmer);
        cardSnakeCharmer.setVisibility(View.GONE);
    } else {
        if (Helpers.doesFileExist(SNAKE_CHARMER_VERSION)) {
            TextView snakeTitle = (TextView) findViewById(R.id.snake_charmer);
            String snakeVersion = CPUHelper.readOneLineNotRoot(SNAKE_CHARMER_VERSION);
            snakeVersion = snakeVersion.replaceAll("version: ", "v");
            snakeTitle.setText(snakeTitle.getText() + " " + snakeVersion);
            if (snakeVersion.equals("v1.2")) {
                TextView snakeDesc = (TextView) findViewById(R.id.snake_charmer_text);
                snakeDesc.setText(snakeDesc.getText() + "\n" + getString(R.string.snake_charmer_built_in));
                snakeCharmer.setEnabled(false);
            }
        }

        if (bootPrefs.getBoolean("SNAKE_CHARMER", true)) {
            snakeCharmer.setChecked(true);
            snakeCharmerEnabled = true;
        }

        snakeCharmer.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isOn) {
                snakeCharmerEnabled = isOn;
            }
        });
    }

    int frequenciesNum = availableFrequencies.length - 1;

    Switch thermalControl = (Switch) findViewById(R.id.msm_thermal_switch);
    if (Helpers.doesFileExist(MSM_THERMAL)) {
        String thermal = CPUHelper.readOneLineNotRoot(MSM_THERMAL);
        if (thermal.equals("Y"))
            thermalControl.setChecked(true);
        else
            thermalControl.setChecked(false);

        thermalControl.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                if (isChecked)
                    Helpers.CMDProcessorWrapper.runSuCommand("echo Y > " + MSM_THERMAL);
                else
                    Helpers.CMDProcessorWrapper.runSuCommand("echo N > " + MSM_THERMAL);

                bootPrefs.edit().putBoolean("MSM_THERMAL", isChecked).commit();
            }
        });
    }
    thermalControl.setChecked(bootPrefs.getBoolean("MSM_THERMAL", true));

    perCoreGovernor = (Switch) findViewById(R.id.per_core_governors_switch);
    perCoreGovernor.setChecked(bootPrefs.getBoolean("PER_CORE_GOV", true));

    if (perCoreGovernor.isChecked()) {
        findViewById(R.id.card_general_governor).setVisibility(View.GONE);
        findViewById(R.id.card_per_core_governors).setVisibility(View.VISIBLE);
    } else {
        findViewById(R.id.card_per_core_governors).setVisibility(View.GONE);
        findViewById(R.id.card_general_governor).setVisibility(View.VISIBLE);
    }

    perCoreGovernor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if (isChecked) {
                findViewById(R.id.card_general_governor).setVisibility(View.GONE);
                findViewById(R.id.card_per_core_governors).setVisibility(View.VISIBLE);
                handleGovernors();
            } else {
                findViewById(R.id.card_per_core_governors).setVisibility(View.GONE);
                findViewById(R.id.card_general_governor).setVisibility(View.VISIBLE);
                handleGovernors();
            }

            bootPrefs.edit().putBoolean("PER_CORE_GOV", isChecked).commit();
        }
    });

    String currentIo = "";
    if (Helpers.doesFileExist(IO_SCHEDULER))
        currentIo = CPUHelper.getIOScheduler();

    String currentTcp = "";
    if (Helpers.doesFileExist(CURR_TCP_ALGORITHM))
        currentTcp = Helpers.getCurrentTcpAlgorithm();

    String curMaxSpeed = "NaN";
    if (Helpers.doesFileExist(MAX_FREQ_ALL_CORES))
        curMaxSpeed = CPUHelper.readOneLineNotRoot(MAX_FREQ_ALL_CORES);
    else if (Helpers.doesFileExist(MAX_FREQ))
        curMaxSpeed = CPUHelper.readOneLineNotRoot(MAX_FREQ);

    String curMinSpeed = "NaN";
    if (Helpers.doesFileExist(MIN_FREQ_ALL_CORES))
        curMinSpeed = CPUHelper.readOneLineNotRoot(MIN_FREQ_ALL_CORES);
    else if (Helpers.doesFileExist(MIN_FREQ))
        curMinSpeed = CPUHelper.readOneLineNotRoot(MIN_FREQ);

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

    if (Helpers.doesFileExist(NUM_OF_CPUS))
        mNumOfCpus = Helpers.getNumOfCpus();

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

    mMaxSlider = (SeekBar) findViewById(R.id.max_slider);
    mMaxSlider.setMax(frequenciesNum);
    mMaxSpeedText = (TextView) findViewById(R.id.max_speed_text);
    mMaxSpeedText.setText(toMHz(curMaxSpeed));
    mMaxSlider.setProgress(Arrays.asList(availableFrequencies).indexOf(curMaxSpeed));
    mMaxSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser)
                setMaxSpeed(seekBar, progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            startSupportActionMode(new ActionMode.Callback() {
                @Override
                public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                    MenuInflater inflater = actionMode.getMenuInflater();
                    inflater.inflate(R.menu.contextual_menu, menu);
                    return true;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.apply:
                        if (mMaxFreqSetting != null && !mMaxFreqSetting.isEmpty()) {
                            bootPrefs.edit().putString("CPU_MAX_FREQ", mMaxFreqSetting).commit();
                            for (int i = 0; i < mNumOfCpus; i++)
                                Helpers.CMDProcessorWrapper.runSuCommand("busybox echo " + mMaxFreqSetting
                                        + " > " + MAX_FREQ.replace("cpu0", "cpu" + i));

                            if (snakeCharmerEnabled)
                                Helpers.CMDProcessorWrapper.runSuCommand(
                                        "busybox echo " + mMaxFreqSetting + " > " + SNAKE_CHARMER_MAX_FREQ);
                        }

                        if (mIsTegra3) {
                            if (mMaxFreqSetting != null && !mMaxFreqSetting.isEmpty())
                                Helpers.CMDProcessorWrapper.runSuCommand(
                                        "busybox echo " + mMaxFreqSetting + " > " + TEGRA_MAX_FREQ);

                            if (snakeCharmerEnabled)
                                Helpers.CMDProcessorWrapper.runSuCommand(
                                        "busybox echo " + mMaxFreqSetting + " > " + SNAKE_CHARMER_MAX_FREQ);
                        }
                        actionMode.finish();
                        return true;
                    default:
                        return false;
                    }
                }

                @Override
                public void onDestroyActionMode(ActionMode actionMode) {

                }
            });
        }
    });

    mMinSlider = (SeekBar) findViewById(R.id.min_slider);
    mMinSlider.setMax(frequenciesNum);
    mMinSpeedText = (TextView) findViewById(R.id.min_speed_text);
    mMinSpeedText.setText(toMHz(curMinSpeed));
    mMinSlider.setProgress(Arrays.asList(availableFrequencies).indexOf(curMinSpeed));
    mMinSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser)
                setMinSpeed(seekBar, progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            startSupportActionMode(new ActionMode.Callback() {
                @Override
                public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
                    MenuInflater inflater = actionMode.getMenuInflater();
                    inflater.inflate(R.menu.contextual_menu, menu);
                    return true;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
                    switch (menuItem.getItemId()) {
                    case R.id.apply:
                        if (mMinFreqSetting != null && !mMinFreqSetting.isEmpty()) {
                            bootPrefs.edit().putString("CPU_MIN_FREQ", mMinFreqSetting).commit();
                            for (int i = 0; i < mNumOfCpus; i++)
                                Helpers.CMDProcessorWrapper.runSuCommand("busybox echo " + mMinFreqSetting
                                        + " > " + MIN_FREQ.replace("cpu0", "cpu" + i));
                        }
                        actionMode.finish();
                        return true;
                    default:
                        return false;
                    }
                }

                @Override
                public void onDestroyActionMode(ActionMode actionMode) {

                }
            });
        }
    });

    handleGovernors();

    /** TCP Congestion Spinner */
    Spinner mTcp = (Spinner) findViewById(R.id.tcp);
    ArrayAdapter<CharSequence> tcpAdapter = new ArrayAdapter<CharSequence>(this, R.layout.spinner_row);
    tcpAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ArrayList<String> algorithms = Helpers.getTcpAlgorithms();
    for (String algorithm : algorithms)
        tcpAdapter.add(algorithm);
    mTcp.setAdapter(tcpAdapter);
    mTcp.setSelection(algorithms.indexOf(currentTcp));
    mTcp.setOnItemSelectedListener(new TCPListener());

    onlineCoresPolling();
}

From source file:nl.hnogames.domoticz.Adapters.DashboardAdapter.java

/**
 * Set the data for a dimmer/* w  ww.j a v a 2  s. c  o  m*/
 *
 * @param mDeviceInfo Device info
 * @param holder      Holder to use
 */
private void setDimmerRowData(final DevicesInfo mDeviceInfo, final DataObjectHolder holder,
        final boolean isRGB) {
    String text;

    holder.isProtected = mDeviceInfo.isProtected();

    if (holder.switch_name != null)
        holder.switch_name.setText(mDeviceInfo.getName());

    if (holder.signal_level != null) {
        text = context.getString(R.string.last_update) + ": "
                + UsefulBits.getFormattedDate(context, mDeviceInfo.getLastUpdateDateTime().getTime());
        holder.signal_level.setText(text);
    }

    if (holder.switch_battery_level != null) {
        text = context.getString(R.string.status) + ": " + String.valueOf(mDeviceInfo.getStatus());
        holder.switch_battery_level.setText(text);
    }

    holder.switch_dimmer_level.setId(mDeviceInfo.getIdx() + ID_TEXTVIEW);
    String percentage = calculateDimPercentage(mDeviceInfo.getMaxDimLevel(), mDeviceInfo.getLevel());
    holder.switch_dimmer_level.setText(percentage);

    Picasso.with(context)
            .load(DomoticzIcons.getDrawableIcon(mDeviceInfo.getTypeImg(), mDeviceInfo.getType(),
                    mDeviceInfo.getSubType(), mDeviceInfo.getStatusBoolean(), mDeviceInfo.getUseCustomImage(),
                    mDeviceInfo.getImage()))
            .into(holder.iconRow);

    if (!mDeviceInfo.getStatusBoolean())
        holder.iconRow.setAlpha(0.5f);
    else
        holder.iconRow.setAlpha(1f);

    holder.dimmerOnOffSwitch.setId(mDeviceInfo.getIdx() + ID_SWITCH);

    holder.dimmerOnOffSwitch.setOnCheckedChangeListener(null);
    holder.dimmerOnOffSwitch.setChecked(mDeviceInfo.getStatusBoolean());
    holder.dimmerOnOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
            handleOnOffSwitchClick(compoundButton.getId(), checked);
            mDeviceInfo.setStatusBoolean(checked);
            if (checked) {
                holder.switch_dimmer_level.setVisibility(View.VISIBLE);
                holder.dimmer.setVisibility(View.VISIBLE);
                if (holder.dimmer.getProgress() <= 10) {
                    holder.dimmer.setProgress(20);//dimmer turned on with default progress value
                }
                if (isRGB)
                    holder.buttonColor.setVisibility(View.VISIBLE);
            } else {
                holder.switch_dimmer_level.setVisibility(View.GONE);
                holder.dimmer.setVisibility(View.GONE);
                if (isRGB)
                    holder.buttonColor.setVisibility(View.GONE);
            }
            if (!checked)
                holder.iconRow.setAlpha(0.5f);
            else
                holder.iconRow.setAlpha(1f);
        }
    });

    holder.dimmer.setProgress(mDeviceInfo.getLevel());
    holder.dimmer.setMax(mDeviceInfo.getMaxDimLevel());
    holder.dimmer.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            String percentage = calculateDimPercentage(seekBar.getMax(), progress);
            TextView switch_dimmer_level = (TextView) seekBar.getRootView()
                    .findViewById(mDeviceInfo.getIdx() + ID_TEXTVIEW);

            if (switch_dimmer_level != null)
                switch_dimmer_level.setText(percentage);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            previousDimmerValue = seekBar.getProgress();
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            int progress = seekBar.getProgress();
            Switch dimmerOnOffSwitch = null;
            try {
                dimmerOnOffSwitch = (Switch) seekBar.getRootView()
                        .findViewById(mDeviceInfo.getIdx() + ID_SWITCH);
                if (progress == 0 && dimmerOnOffSwitch.isChecked()) {
                    dimmerOnOffSwitch.setChecked(false);
                    seekBar.setProgress(previousDimmerValue);
                } else if (progress > 0 && !dimmerOnOffSwitch.isChecked()) {
                    dimmerOnOffSwitch.setChecked(true);
                }
            } catch (Exception ex) {
                /*else we don't use a switch, but buttons */}

            handleDimmerChange(mDeviceInfo.getIdx(), progress + 1, false);
            mDeviceInfo.setLevel(progress);
        }
    });

    if (!mDeviceInfo.getStatusBoolean()) {
        holder.switch_dimmer_level.setVisibility(View.GONE);
        holder.dimmer.setVisibility(View.GONE);
        if (isRGB)
            holder.buttonColor.setVisibility(View.GONE);
    } else {
        holder.switch_dimmer_level.setVisibility(View.VISIBLE);
        holder.dimmer.setVisibility(View.VISIBLE);
        if (isRGB)
            holder.buttonColor.setVisibility(View.VISIBLE);
    }

    if (holder.buttonLog != null) {
        holder.buttonLog.setId(mDeviceInfo.getIdx());
        holder.buttonLog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleLogButtonClick(v.getId());
            }
        });
    }

    if (isRGB && holder.buttonColor != null) {
        holder.buttonColor.setId(mDeviceInfo.getIdx());
        holder.buttonColor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                handleColorButtonClick(v.getId());
            }
        });
    }
}