Example usage for android.widget Switch Switch

List of usage examples for android.widget Switch Switch

Introduction

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

Prototype

public Switch(Context context) 

Source Link

Document

Construct a new Switch with default styling.

Usage

From source file:com.readystatesoftware.ghostlog.MainActivity.java

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

    Switch mainSwitch = new Switch(this);
    mainSwitch.setChecked(LogService.isRunning());
    mainSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override//w ww  .  j a  v  a 2s  .c  o  m
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            Intent intent = new Intent(MainActivity.this, LogService.class);
            if (b) {
                if (!LogService.isRunning()) {
                    startService(intent);
                }
            } else {
                stopService(intent);
            }
        }
    });

    final ActionBar bar = getActionBar();
    final ActionBar.LayoutParams lp = new ActionBar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT);
    lp.gravity = Gravity.RIGHT | Gravity.CENTER_VERTICAL;
    lp.rightMargin = getResources().getDimensionPixelSize(R.dimen.main_switch_margin_right);
    bar.setCustomView(mainSwitch, lp);
    bar.setDisplayShowCustomEnabled(true);

    mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (!mPrefs.getBoolean(PreferenceManager.KEY_HAS_SET_DEFAULT_VALUES, false)) {
        PreferenceManager.setDefaultValues(this, R.xml.pref_filters, true);
        PreferenceManager.setDefaultValues(this, R.xml.pref_appearance, true);
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean(PreferenceManager.KEY_HAS_SET_DEFAULT_VALUES, true);
        edit.apply();
    }

}

From source file:org.telegram.ui.Cells.TextCheckCell.java

public TextCheckCell(Context context) {
    super(context);

    setElevation(AndroidUtilities.dp(2));
    setBackgroundColor(ContextCompat.getColor(context, R.color.card_background));

    if (paint == null) {
        paint = new Paint();
        paint.setColor(ContextCompat.getColor(context, R.color.divider) /*0xffd9d9d9*/);
        paint.setStrokeWidth(1);/*from w  w w.j a v  a 2s  . c o  m*/
    }

    textView = new TextView(context);
    textView.setTextColor(ContextCompat.getColor(context, R.color.primary_text)/*0xff212121*/);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
    textView.setLines(1);
    textView.setMaxLines(1);
    textView.setSingleLine(true);
    textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL);
    textView.setEllipsize(TextUtils.TruncateAt.END);
    addView(textView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP,
                    LocaleController.isRTL ? 64 : 17, 0, LocaleController.isRTL ? 17 : 64, 0));

    valueTextView = new TextView(context);
    valueTextView.setTextColor(ContextCompat.getColor(context, R.color.secondary_text)/*0xff212121*/);
    valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13);
    valueTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT);
    valueTextView.setLines(1);
    valueTextView.setMaxLines(1);
    valueTextView.setSingleLine(true);
    valueTextView.setPadding(0, 0, 0, 0);
    valueTextView.setEllipsize(TextUtils.TruncateAt.END);
    addView(valueTextView,
            LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
                    (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP,
                    LocaleController.isRTL ? 64 : 17, 35, LocaleController.isRTL ? 17 : 64, 0));

    checkBox = new Switch(context);
    checkBox.setDuplicateParentStateEnabled(false);
    checkBox.setFocusable(false);
    checkBox.setFocusableInTouchMode(false);
    checkBox.setClickable(false);
    checkBox.setBackground(null);
    addView(checkBox, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT,
            (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL, 12, 0, 12, 0));
}

From source file:com.android.settings.profiles.ProfilesSettings.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // We don't call super.onActivityCreated() here, since it assumes we already set up
    // Preference (probably in onCreate()), while ProfilesSettings exceptionally set it up in
    // this method.
    // On/off switch
    Activity activity = getActivity();// ww  w.  ja v a  2 s . c  o m
    //Switch
    mActionBarSwitch = new Switch(activity);

    if (activity instanceof PreferenceActivity) {
        PreferenceActivity preferenceActivity = (PreferenceActivity) activity;
        if (preferenceActivity.onIsHidingHeaders() || !preferenceActivity.onIsMultiPane()) {
            final int padding = activity.getResources()
                    .getDimensionPixelSize(R.dimen.action_bar_switch_padding);
            mActionBarSwitch.setPaddingRelative(0, 0, padding, 0);
            activity.getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM,
                    ActionBar.DISPLAY_SHOW_CUSTOM);
            activity.getActionBar().setCustomView(mActionBarSwitch,
                    new ActionBar.LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,
                            ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.END));
        }
    }

    mProfileEnabler = new ProfileEnabler(activity, mActionBarSwitch);

    // After confirming PreferenceScreen is available, we call super.
    super.onActivityCreated(savedInstanceState);
}

From source file:samsungsami.io.example.samiremotecontrol.DeviceActivity.java

/**
 * Fill the device status and info table
 *///from   w  ww .j a  va  2 s .c  om
void fillTable() {

    TableRow row;
    TextView t1, t2, t3;
    for (int current = 0; current < fields.size(); current++) {
        row = new TableRow(this);
        t1 = new TextView(this);
        t1.setTextColor(Color.GRAY);
        t2 = new TextView(this);
        t2.setTextColor(Color.BLACK);
        t3 = new TextView(this);
        t3.setTextColor(Color.BLACK);

        t1.setText(fields.get(current));
        t2.setText(values.get(current));
        t3.setText(units.get(current));

        t1.setTextSize(15);
        t2.setTextSize(15);
        t3.setTextSize(15);

        row.addView(t1);

        if (fields.get(current).equals("state")) {
            Switch toggle = new Switch(this);
            toggle.setChecked(values.get(current).toLowerCase().equals("on"));
            toggle.setEnabled(false);
            row.addView(toggle);
        } else
            row.addView(t2);

        row.addView(t3);
        propertiesTableLayout.addView(row, new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        // Adjust the view
        propertiesTableLayout.setColumnStretchable(0, true);
        propertiesTableLayout.setColumnStretchable(1, true);
        propertiesTableLayout.setColumnStretchable(2, true);
    }
}

From source file:org.mozilla.mozstumbler.client.navdrawer.MainDrawerActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);

    mMenuItemStartStop = menu.add(Menu.NONE, MENU_START_STOP, Menu.NONE, R.string.start_scanning);
    if (Build.VERSION.SDK_INT >= 14) {
        Switch s = new Switch(this);
        s.setChecked(false);/*  w ww . ja v  a  2  s .co m*/
        s.setOnCheckedChangeListener(mStartStopButtonListener);
        mMenuItemStartStop.setActionView(s);
        mMenuItemStartStop.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    } else {
        MenuItemCompat.setShowAsAction(mMenuItemStartStop, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
    }

    updateStartStopMenuItemState();
    return true;
}

From source file:org.borderstone.tagtags.TTProtocolActivity.java

@Override
public void onCreate(Bundle bundle) {
    super.onCreate(bundle);

    this.setContentView(R.layout.activity_protocol);

    this.setTheme(R.style.AppTheme);

    if (Constants.files.contains(Constants.filename)) {
        int idex = Constants.files.indexOf(Constants.filename);
        row = Constants.file_rows.get(idex);
    }/*from  ww  w. j  a  v a 2 s  .co  m*/

    lblGlobal = new BTitleLabel(this);
    lblLocal = new BTitleLabel(this);
    btnUpload = new BButton(this);

    lblGlobal.setPadding(15, 15, 15, 15);
    lblLocal.setPadding(15, 15, 15, 15);
    lblGlobal.setGravity(Gravity.CENTER);
    lblLocal.setGravity(Gravity.CENTER);
    lblLocal.setTextColor(Color.WHITE);
    lblGlobal.setTextColor(Color.WHITE);
    lblLocal.setTextSize(Constants.fontSize + 2);
    lblGlobal.setTextSize(Constants.fontSize + 2);

    lblGlobal.setText("GLOBAL PROPERTIES");
    lblLocal.setText("TECHNICAL MATERIAL");

    widgetLayout = new BMultiColumnLayout(this);
    mDrawerList = (LinearLayout) this.findViewById(R.id.protocolDrawer);

    lockSwitch = new Switch(this);

    btnUpload.setOnClickListener(this);

    btnUpload.setIcon(R.drawable.upload);
    btnUpload.setText("Upload data");

    btnGPS = new ImageButton(this);

    btnGPS.setOnClickListener(this);
    btnGPS.setLongClickable(true);
    btnGPS.setOnLongClickListener(this);

    DisplayMetrics metrics = getResources().getDisplayMetrics();
    DrawerLayout.LayoutParams lp = new DrawerLayout.LayoutParams(metrics.densityDpi * 2,
            LinearLayout.LayoutParams.MATCH_PARENT);
    lp.gravity = Gravity.START;

    sv = (ScrollView) this.findViewById(R.id.protocolBack);

    widgetLayout.setLayoutParams(Constants.defaultParams);

    sv.addView(widgetLayout);
    sv.setLayoutTransition(new LayoutTransition());

    toolbar = (Toolbar) this.findViewById(R.id.protToolbar);
    this.setSupportActionBar(toolbar);

    toolbar.setNavigationIcon(R.drawable.drawer);

    toolbar.inflateMenu(R.menu.protocol_menu);

    toolbar.addView(lockSwitch);

    lblPercent = new BTitleLabel(this);
    lblInfo = new BInfoLabel(this);

    drawProtocolPage();

    widgetLayout.setFocusable(true);
    widgetLayout.setFocusableInTouchMode(true);
    widgetLayout.requestFocus();

    mDrawerList.bringToFront();

    final DrawerLayout drawerLayout = (DrawerLayout) this.findViewById(R.id.drawerLayoutProtocol);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!drawerLayout.isDrawerOpen(Gravity.LEFT))
                drawerLayout.openDrawer(Gravity.LEFT);
            else
                drawerLayout.closeDrawer(Gravity.LEFT);
        }
    });
}

From source file:com.example.android.apprestrictionenforcer.AppRestrictionEnforcerFragment.java

private void updateApprovals(Context context, String[] approvals, String[] selectedApprovals) {
    mCurrentRestrictions.putStringArray(RESTRICTION_KEY_APPROVALS, selectedApprovals);
    mLayoutApprovals.removeAllViews();/*w w  w.  ja v  a 2s  .  c  om*/
    for (String approval : approvals) {
        Switch sw = new Switch(context);
        sw.setText(approval);
        sw.setTag(approval);
        sw.setChecked(Arrays.asList(selectedApprovals).contains(approval));
        sw.setOnCheckedChangeListener(this);
        sw.setId(R.id.approval);
        mLayoutApprovals.addView(sw);
    }
}

From source file:com.artemchep.horario.ui.activities.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    requestCheckout(); // enable in-app-billing for this activity
    super.onCreate(savedInstanceState);
    // Apply current theme
    switch (Config.getInstance().getInt(Config.KEY_UI_THEME)) {
    case Config.THEME_LIGHT:
        setTheme(R.style.AppThemeLight_NoActionBar);
        break;/*from w ww  . ja  v  a 2s .  c  o m*/
    case Config.THEME_DARK:
        setTheme(R.style.AppTheme_NoActionBar);
        break;
    case Config.THEME_BLACK:
        setTheme(R.style.AppThemeBlack_NoActionBar);
        break;
    }

    setContentView(R.layout.activity_main);

    mConfig.addListener(this, Config.KEY_HOLIDAY_ON, Config.KEY_ADDRESS);
    String address = mConfig.getString(Config.KEY_ADDRESS);
    mAddress = Address.fromString(address);

    // Analytics
    mAnalytics = FirebaseAnalytics.getInstance(this);

    // Setup other views
    mDrawer = (DrawerLayout) findViewById(R.id.drawer);
    mContainers = (ContainersLayout) mDrawer.findViewById(R.id.containers);
    mAppBar = (CustomAppBar) mContainers.findViewById(R.id.activity_main__custom_appbar);
    mFab = (FloatingActionButton) mContainers.findViewById(R.id.fab);

    Toolbar toolbar = mAppBar.hasGeneralToolbar() ? mAppBar.getToolbarGeneral() : mAppBar.getToolbarSpecific();
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawer, toolbar, 0, 0) {

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            promptAccountHeader();
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            mAccountHeaderView.hideAccountList();
        }

    };
    mDrawerToggle.setDrawerIndicatorEnabled(true);
    mDrawer.addDrawerListener(mDrawerToggle);
    mDrawerToggle.syncState();

    // Setup navigation views
    mNavSideView = (NavigationView) mDrawer.findViewById(R.id.nav_side);
    if (mNavSideView != null) {
        mNavSideView.setNavigationItemSelectedListener(this);
    }
    mNavView = (NavigationView) mDrawer.findViewById(R.id.nav);
    mNavView.setNavigationItemSelectedListener(this);
    mAccountHeaderView = (AccountHeaderView) mNavView.getHeaderView(0).findViewById(R.id.account_header);
    mAccountHeaderView.setOnCurrentProfileChangedListener(this);
    mAccountHeaderView.setOnProfileClickListener(this);
    mAccountHeaderView.setEmptyTitleText(getString(R.string.nav_profile_empty));
    // Setup holidays mode item
    mHolidaysModeSwitch = new Switch(this);
    mHolidaysModeSwitch.setChecked(mConfig.getBoolean(Config.KEY_HOLIDAY_ON));
    mHolidaysModeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (mHolidaysModeBroadcasting) {
                return;
            }

            // Commit the changes
            mConfig.edit(MainActivity.this).put(Config.KEY_HOLIDAY_ON, isChecked).commit(MainActivity.this);
        }
    });
    mNavView.getMenu().findItem(R.id.nav_holidays_mode).setActionView(mHolidaysModeSwitch);

    if (savedInstanceState != null) {
        mMasterFragment = getSupportFragmentManager().getFragment(savedInstanceState, TAG_FRAGMENT_MASTER);
        mDetailsFragment = getSupportFragmentManager().getFragment(savedInstanceState, TAG_FRAGMENT_DETAILS);

        // Restore CAB only if corresponding fragment still exists
        // and provides the callback, otherwise create it from scratch.
        if (mMasterFragment != null && mMasterFragment instanceof MaterialCab.Callback) {
            mCabCallbackExt = (MaterialCab.Callback) mMasterFragment;
            mCab = MaterialCab.restoreState(savedInstanceState, this, mCabCallback);
        }
    }

    if (mCab == null) {
        mCab = new MaterialCab(this, R.id.cab_stub);
    }

    // Get current user
    mAuth = FirebaseAuth.getInstance();
    mAuth.addAuthStateListener(this);
    FirebaseUser user = mAuth.getCurrentUser();
    if (user == null) {
        switchToAuthActivity();
        return;
    } else {
        mUserId = user.getUid();
        // register new listener
        DatabaseReference ref = Db.user(mUserId).timetable(null).ref();
        ref.addChildEventListener(mAccountHeaderUpdateListener);

        if (savedInstanceState == null) {
            int id = retrieveStartupItem();
            onNavigationItemSelected(mNavView.getMenu().findItem(id));
        }
    }

    // Show updated changelog each time application version
    // code is increased.
    if (!AboutDialog.isChangelogRead(this)) {
        DialogHelper.showAboutDialog(this, AboutDialog.VIEW_CHANGELOG);
    }
}

From source file:net.opendasharchive.openarchive.ReviewMediaActivity.java

private void deleteMedia() {
    final Switch swDeleteLocal = new Switch(this);
    final Switch swDeleteRemote = new Switch(this);

    LinearLayout linearLayoutGroup = new LinearLayout(this);
    linearLayoutGroup.setOrientation(LinearLayout.VERTICAL);
    linearLayoutGroup.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));

    swDeleteLocal.setTextOn(getString(R.string.answer_yes));
    swDeleteLocal.setTextOff(getString(R.string.answer_no));

    TextView tvLocal = new TextView(this);
    tvLocal.setText(R.string.delete_local);

    LinearLayout linearLayout = new LinearLayout(this);
    linearLayout.setOrientation(LinearLayout.HORIZONTAL);
    linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    linearLayout.setGravity(Gravity.CENTER_HORIZONTAL);

    linearLayout.addView(tvLocal);//from  w ww.  ja va2  s.c o  m
    linearLayout.addView(swDeleteLocal);

    linearLayoutGroup.addView(linearLayout);

    if (mMedia.getServerUrl() != null) {
        swDeleteRemote.setTextOn(getString(R.string.answer_yes));
        swDeleteRemote.setTextOff(getString(R.string.answer_no));

        TextView tvRemote = new TextView(this);
        tvRemote.setText(R.string.delete_remote);

        LinearLayout linearLayoutRemote = new LinearLayout(this);
        linearLayoutRemote.setOrientation(LinearLayout.HORIZONTAL);
        linearLayoutRemote.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        linearLayoutRemote.setGravity(Gravity.CENTER_HORIZONTAL);

        linearLayoutRemote.addView(tvRemote);
        linearLayoutRemote.addView(swDeleteRemote);
        linearLayoutGroup.addView(linearLayoutRemote);

    }

    AlertDialog.Builder build = new AlertDialog.Builder(ReviewMediaActivity.this).setTitle(R.string.menu_delete)
            .setMessage(R.string.alert_delete_media).setView(linearLayoutGroup).setCancelable(true)
            .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    //do nothing
                }
            })

            .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    deleteMedia(swDeleteLocal.isChecked(), swDeleteRemote.isChecked());
                    finish();

                }
            });

    build.create().show();
}

From source file:com.juick.android.MainActivity.java

@TargetApi(VERSION_CODES.ICE_CREAM_SANDWICH)
private void selectSourcesForCombined(final String prefix, final String[] codes) {
    final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    ScrollView v = new ScrollView(this);
    v.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    final LinearLayout ll = new LinearLayout(this);
    ll.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));
    ll.setOrientation(LinearLayout.VERTICAL);
    v.addView(ll);/*from   ww  w  . j a  v a2s . c o  m*/
    for (int i = 0; i < codes.length; i++) {
        final CompoundButton sw = VERSION.SDK_INT >= 14 ? new Switch(this) : new CheckBox(this);
        sw.setPadding(10, 10, 10, 10);
        sw.setLayoutParams(new ScrollView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        sw.setText(codes[i]);
        sw.setChecked(sp.getBoolean(prefix + codes[i], true));
        ll.addView(sw);
    }

    new AlertDialog.Builder(MainActivity.this).setView(v).setCancelable(true)
            .setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    SharedPreferences.Editor e = sp.edit();
                    for (int i = 0; i < ll.getChildCount(); i++) {
                        CompoundButton cb = (CompoundButton) ll.getChildAt(i);
                        assert cb != null;
                        e.putBoolean(prefix + codes[i], cb.isChecked());
                    }
                    e.commit();
                }
            }).create().show();

}