下面列出了怎么用android.widget.Switch的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Clear listener in Switch for specify ViewGroup.
*
* @param viewGroup The ViewGroup that will need to clear the listener.
*/
private void clearListenerInViewGroup(final ViewGroup viewGroup) {
if (null == viewGroup) {
return;
}
int count = viewGroup.getChildCount();
for(int n = 0; n < count; ++n) {
View childView = viewGroup.getChildAt(n);
if(childView instanceof Switch) {
final Switch switchView = (Switch) childView;
switchView.setOnCheckedChangeListener(null);
return;
} else if (childView instanceof ViewGroup){
ViewGroup childGroup = (ViewGroup)childView;
clearListenerInViewGroup(childGroup);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
MenuItem menuItem = menu.findItem(R.id.menu_item_switch);
if (menuItem == null) {
return false;
}
switchProxy = (Switch) menuItem.getActionView();
if (switchProxy == null) {
return false;
}
switchProxy.setChecked(LocalVpnService.IsRunning);
switchProxy.setOnCheckedChangeListener(this);
return true;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
// Bind event listeners and initial states
view.findViewById(R.id.set_chrome_restrictions).setOnClickListener(this);
view.findViewById(R.id.clear_chrome_restrictions).setOnClickListener(this);
view.findViewById(R.id.enable_forwarding).setOnClickListener(this);
view.findViewById(R.id.disable_forwarding).setOnClickListener(this);
view.findViewById(R.id.send_intent).setOnClickListener(this);
mButtonRemoveProfile = (Button) view.findViewById(R.id.remove_profile);
mButtonRemoveProfile.setOnClickListener(this);
Switch toggleCalculator = (Switch) view.findViewById(R.id.toggle_calculator);
toggleCalculator.setChecked(mCalculatorEnabled);
toggleCalculator.setOnCheckedChangeListener(this);
Switch toggleChrome = (Switch) view.findViewById(R.id.toggle_chrome);
toggleChrome.setChecked(mChromeEnabled);
toggleChrome.setOnCheckedChangeListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
Switch switchSvc = (Switch) menu.findItem(R.id.action_svc_switch).getActionView().findViewById(R.id.switch_svc);
switchSvc.setChecked(settings.isServiceEnabled());
switchSvc.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
setSvcEnabled(isChecked);
}
});
return true;
}
/**
* Defines the active Switch
* @param v used view
* @param pos item pos
*/
private void defineActiveSwitch(View v, final int pos){
Switch switchReference = v.findViewById(R.id.on_switch);
switchReference.setChecked(getItem(pos).getCalculationModuleReference().getActive());
switchReference.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getItem(pos).getCalculationModuleReference().setActive(isChecked);
String notificationText;
if (isChecked)
notificationText = "Calculations activated";
else
notificationText = "Calculations deactivated";
Snackbar snackbar = Snackbar
.make(mainView, notificationText, Snackbar.LENGTH_SHORT);
snackbar.show();
}
});
}
/**
* Clear listener in Switch for specify ViewGroup.
*
* @param viewGroup The ViewGroup that will need to clear the listener.
*/
private void clearListenerInViewGroup(ViewGroup viewGroup) {
if (null == viewGroup) {
return;
}
int count = viewGroup.getChildCount();
for(int n = 0; n < count; ++n) {
View childView = viewGroup.getChildAt(n);
if(childView instanceof Switch) {
final Switch switchView = (Switch) childView;
switchView.setOnCheckedChangeListener(null);
return;
} else if (childView instanceof ViewGroup){
ViewGroup childGroup = (ViewGroup)childView;
clearListenerInViewGroup(childGroup);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_map, container, false);
// Inflate the layout for this fragment
switchLocation = (Switch) view.findViewById(R.id.switchLocation);
switchLBSTrace = (Switch) view.findViewById(R.id.switchLBSTrace);
switchLocation.setOnCheckedChangeListener(this);
switchLBSTrace.setOnCheckedChangeListener(this);
mMapView = (TextureMapView) view.findViewById(R.id.bmapView);
baiduMap = mMapView.getMap();
baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, false, null));
application.setMaxZoomLevel(baiduMap.getMaxZoomLevel());
// 开启定位图层
baiduMap.setMyLocationEnabled(true);
baiduMap.setOnMarkerClickListener(this);
//再次进入地图fragment时界面刷新
if (application.latLng != null) {
MapStatusUpdate u = MapStatusUpdateFactory.newLatLngZoom(application.getLatLng(), application.getMaxZoomLevel() - 2);
baiduMap.animateMapStatus(u);//动画移动摄像头
if (radarNearbyInfoList != null) {
refreshMapUI();
}
}
return view;
}
@Override
void initView(View view) {
btnHomePoint = (LinearLayout) view.findViewById(R.id.btn_home_point);
tvHomePosition = (TextView) view.findViewById(R.id.tv_home_position);
btnClearMemLevel = (LinearLayout) view.findViewById(R.id.btn_clear_mem_level);
tvClearMemLevel = (TextView) view.findViewById(R.id.tv_clear_mem_level);
btnIconSize = (LinearLayout) view.findViewById(R.id.btn_icon_size);
tvIconSize = (TextView) view.findViewById(R.id.tv_icon_size);
// swHook90 = (Switch) findViewById(R.id.sw_hook_90);
swRootDown = (Switch) view.findViewById(R.id.sw_root_down);
settingAboutMarshmallow = (LinearLayout) view.findViewById(R.id.setting_about_marshmallow);
swChameleonNavbar = (Switch) view.findViewById(R.id.sw_chameleon_navbar);
btnNavbarHeight = (LinearLayout) view.findViewById(R.id.btn_navbar_height);
tvNavbarHeight = (TextView) view.findViewById(R.id.tv_navbar_height);
swVibrate = (Switch) view.findViewById(R.id.sw_navbar_vibrate);
swHideAppIcon = (Switch) view.findViewById(R.id.sw_hide_app_icon);
swNavbarHeight = (Switch) view.findViewById(R.id.sw_navbar_height);
swGoHome = (Switch) view.findViewById(R.id.sw_go_home);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup root) {
final Context context = root.getContext();
checked = new BooleanPreference(
context.getSharedPreferences(getKey(),Context.MODE_PRIVATE),
getTitle(),
String.valueOf(defaultValue));
if(!checked.isSet()) checked.set(defaultValue);
aSwitch = new Switch(new ContextThemeWrapper(context, R.style.Widget_U2020_DebugDrawer_RowWidget));
aSwitch.setText(title);
aSwitch.setChecked(checked.get());
aSwitch.setEnabled(isEnabled());
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checked.set(isChecked);
onSwitch(isChecked);
}
});
aSwitch.setGravity(Gravity.START | Gravity.END | Gravity.CENTER_VERTICAL); // "start|end|center_vertical"
return aSwitch;
}
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_activity);
ButterKnife.inject(this);
pagerView.setAdapter(new SamplePagerAdapter(this));
Switch enabledSwitch = new Switch(this);
enabledSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (first) {
first = false;
Toast.makeText(SampleActivity.this, R.string.first_run, LENGTH_LONG).show();
}
scalpelView.setLayerInteractionEnabled(isChecked);
invalidateOptionsMenu();
}
});
ActionBar actionBar = getActionBar();
actionBar.setCustomView(enabledSwitch);
actionBar.setDisplayOptions(DISPLAY_SHOW_TITLE | DISPLAY_SHOW_CUSTOM);
}
/**
* Constructor
* @param itemView View to be created
* @param backListener - A click listener which should set the RecyclerView to contain the
* list of GeoPackages again
*/
public HeaderViewHolder(View itemView, View.OnClickListener backListener,
DetailActionListener actionListener, EnableAllLayersListener enableAllListener,
GeoPackageDatabase db) {
super(itemView);
detailHeaderMain = (View)itemView.findViewById(R.id.detailHeaderMain);
textName = (TextView) itemView.findViewById(R.id.headerTitle);
textSize = (TextView) itemView.findViewById(R.id.headerSize);
textFeatures = (TextView) itemView.findViewById(R.id.header_text_features);
textTiles = (TextView) itemView.findViewById(R.id.header_text_tiles);
backArrow = (ImageButton) itemView.findViewById(R.id.detailPageBackButton);
enableAllSwitch = (Switch) itemView.findViewById(R.id.header_all_switch);
backArrow.setOnClickListener(backListener);
this.actionListener = actionListener;
mEnableAllListener = enableAllListener;
mDb = db;
setActionButtonListeners();
ViewAnimation.setSlideInFromRightAnimation(detailHeaderMain, 200);
}
public void switchStatus(Switch aSwitch, final String fileName, final int flag) {
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences settings = getActivity().getSharedPreferences(fileName, Context.MODE_PRIVATE);
SharedPreferences.Editor edit = settings.edit();
edit.putBoolean("ischecked", isChecked);
edit.apply();
if (isChecked) {
if (flag == 2) {
getActivity().startService(new Intent(getActivity(), NotificationService.class));
}
}else{
if (flag == 2) {
getActivity().stopService(new Intent(getActivity(), NotificationService.class));
}
}
}
});
}
@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
View view = inflater.inflate(R.layout.debug_drawer_mock_ble, parent, false);
Switch mockBle = view.findViewById(R.id.debug_drawer_ble_mock);
mockBle.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked) {
mainActivity.provideBluetoothUtil(new BluetoothUtilMockImpl());
} else {
mainActivity.provideBluetoothUtil(new BluetoothUtilImpl());
}
});
return view;
}
/**
* Clear listener in Switch for specify ViewGroup.
*
* @param viewGroup The ViewGroup that will need to clear the listener.
*/
private void clearListenerInViewGroup(final ViewGroup viewGroup) {
if (null == viewGroup) {
return;
}
int count = viewGroup.getChildCount();
for (int n = 0; n < count; ++n) {
View childView = viewGroup.getChildAt(n);
if (childView instanceof Switch) {
final Switch switchView = (Switch) childView;
switchView.setOnCheckedChangeListener(null);
return;
} else if (childView instanceof ViewGroup) {
ViewGroup childGroup = (ViewGroup) childView;
clearListenerInViewGroup(childGroup);
}
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
// Retain references for the UI elements
mSwitchSayHello = (Switch) view.findViewById(R.id.say_hello);
mEditMessage = (EditText) view.findViewById(R.id.message);
mEditNumber = (EditText) view.findViewById(R.id.number);
mSpinnerRank = (Spinner) view.findViewById(R.id.rank);
mLayoutApprovals = (LinearLayout) view.findViewById(R.id.approvals);
mLayoutItems = (LinearLayout) view.findViewById(R.id.items);
view.findViewById(R.id.item_add).setOnClickListener(this);
View bundleArrayLayout = view.findViewById(R.id.bundle_array_layout);
if (BUNDLE_SUPPORTED) {
bundleArrayLayout.setVisibility(View.VISIBLE);
} else {
bundleArrayLayout.setVisibility(View.GONE);
}
}
private Switch.OnCheckedChangeListener listener(final int roll) {
return new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (roll == ROLL.READ.ordinal()) {
Extra.getInstance(getBaseContext()).setRead(isChecked);
} else if (roll == ROLL.SEEN.ordinal()) {
Extra.getInstance(getBaseContext()).setSeen(isChecked);
} else if (roll == ROLL.DELIVERED.ordinal()) {
Extra.getInstance(getBaseContext()).setDelivered(isChecked);
} else if (roll == ROLL.SLOT.ordinal()) {
Extra.getInstance(getBaseContext()).setSLOT_ENABLED(isChecked);
} else if (roll == ROLL.IMSI.ordinal()) {
Extra.getInstance(getBaseContext()).setIMSI_ENABLED(isChecked);
} else if (roll == ROLL.REPLY_PATH.ordinal()) {
Extra.getInstance(getBaseContext()).setREPLY_PATH_PRESENT(isChecked);
} else if (roll == ROLL.SERVICE_CENTER.ordinal()) {
Extra.getInstance(getBaseContext()).setServiceCenterBool(isChecked);
} else if (roll == ROLL.TIME_DIFFERENCE.ordinal()) {
Extra.getInstance(getBaseContext()).setTimeDifferenceBool(isChecked);
} else if (roll == ROLL.STATUS.ordinal()) {
Extra.getInstance(getBaseContext()).setSmsStatusBool(isChecked);
}
}
};
}
public SettingsMenu(final Context context) {
super(context);
ViewInspector.runtimeComponentMap.get(context).inject(this);
inflate(context, R.layout.view_inspector_settings_menu, this);
Switch logViewEventsSwitch = (Switch) findViewById(R.id.log_view_events_switch);
logViewEventsSwitch.setChecked(logViewEvents.get());
logViewEventsSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
logViewEvents.set(isChecked);
}
});
View viewFilter = findViewById(R.id.view_filter);
viewFilter.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
new SetViewFilterDialog(
new ContextThemeWrapper(context, BaseDialog.getDialogTheme(context))).show();
}
});
}
/**
* Called when switch is toggled - starts or stops advertising.
*/
@Override
public void onClick(View v) {
// Is the toggle on?
boolean on = ((Switch) v).isChecked();
if (on) {
startAdvertising();
} else {
stopAdvertising();
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.business1).setOnClickListener(this);
findViewById(R.id.business2).setOnClickListener(this);
findViewById(R.id.business3).setOnClickListener(this);
findViewById(R.id.business4).setOnClickListener(this);
JsLoaderUtil.jsState.isFilePrior = true;
//模拟下载Bundle到本地File
JsLoaderUtil.setDefaultFileDir(getApplication());
File file = FileUtil.copyAssetsFile(this, "bundle.zip");
FileUtil.unZip(file, getFilesDir().getAbsolutePath());
SpConfig.setIndex(0);
common1 = findViewById(R.id.intent_to_common1);
common1.setOnClickListener(this);
common2 = findViewById(R.id.intent_to_common2);
common2.setOnClickListener(this);
Switch aSwitch = findViewById(R.id.runtime_switch);
aSwitch.setChecked(SpConfig.getLoadRuntime());
setCheck(SpConfig.getLoadRuntime());
aSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
SpConfig.setLoadRuntime(isChecked);
setCheck(isChecked);
});
JsLoaderUtil.jsState.bundleName = "business3";
JsLoaderUtil.load(getApplication());
}
private void setupSettingsSwitch(int containerId, int labelId, int switchId, boolean checked,
CompoundButton.OnCheckedChangeListener checkedChangeListener) {
ViewGroup container = findViewById(containerId);
String switchLabel = ((TextView) container.findViewById(labelId)).getText().toString();
final Switch switchView = container.findViewById(switchId);
switchView.setContentDescription(switchLabel);
switchView.setChecked(checked);
container.setOnClickListener((view) -> switchView.performClick());
switchView.setOnCheckedChangeListener(checkedChangeListener);
}
private void setupEnabledSwitch() {
Switch enabledSwitch = (Switch) findViewById(R.id.debug_enabled);
enabledSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
setEnabled(isChecked);
}
});
}
private void setupShowVerticalSwitch() {
Switch showVerticalSwitch = (Switch) findViewById(R.id.debug_show_vertical);
showVerticalSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
setDrawVerticalLines(isChecked);
}
});
}
@Override
public int getColor(Switch view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && view.getThumbTintList() != null) {
return view.getThumbTintList().getDefaultColor();
}
return 0;
}
/**
* Fill the fields with the selected account when editing a new account
*/
private void fillFields() {
// Get the user inputs :
((EditText) findViewById(R.id.urlShaarliView)).setText(account.getUrlShaarli());
((EditText) findViewById(R.id.usernameView)).setText(account.getUsername());
((EditText) findViewById(R.id.passwordView)).setText(account.getPassword());
((EditText) findViewById(R.id.shortNameView)).setText(account.getShortName());
((EditText) findViewById(R.id.restapiView)).setText(account.getRestAPIKey());
((Switch) findViewById(R.id.passwordAuthCheckbox)).setChecked(
!(account.getRestAPIKey().length() > 0)
);
togglePasswordAuth(findViewById(R.id.passwordAuthCheckbox));
if (!"".equals(account.getBasicAuthUsername())) {
((EditText) findViewById(R.id.basicUsernameView)).setText(account.getBasicAuthUsername());
((EditText) findViewById(R.id.basicPasswordView)).setText(account.getBasicAuthPassword());
((Switch) findViewById(R.id.basicAuthSwitch)).setChecked(true);
enableBasicAuth(findViewById(R.id.basicAuthSwitch));
}
// default account?
SharedPreferences prefs = getSharedPreferences(getString(R.string.params), MODE_PRIVATE);
this.isDefaultAccount = (prefs.getLong(getString(R.string.p_default_account), -1) == account.getId());
((CheckBox) findViewById(R.id.defaultAccountCheck)).setChecked(this.isDefaultAccount);
findViewById(R.id.deleteAccountButton).setVisibility(View.VISIBLE);
}
public AppViewHolder(View view) {
super(view);
icon = (ImageView) itemView.findViewById(R.id.itemicon);
check = (Switch) itemView.findViewById(R.id.itemcheck);
itemView.setOnClickListener(this);
}
/**
* Open a dialog for the user to change the description of the share
*/
private void openDialog() {
setContentView(R.layout.activity_share);
initAccountSpinner();
if (NetworkUtils.isUrl(defaults.getUrl())) {
prefetchLink(defaults);
autoLoadTitleAndDescription(defaults);
updateLoadersVisibility();
}
((EditText) findViewById(R.id.url)).setText(defaults.getUrl());
MultiAutoCompleteTextView textView = findViewById(R.id.tags);
((EditText) findViewById(R.id.tags)).setText(defaults.getTags());
new AutoCompleteWrapper(textView, this);
((Checkable) findViewById(R.id.private_share)).setChecked(defaults.isPrivate());
// Init the tweet button if necessary:
Switch tweetCheckBox = findViewById(R.id.tweet);
tweetCheckBox.setChecked(userPrefs.isTweet());
if (!userPrefs.isTweet()) {
tweetCheckBox.setVisibility(View.GONE);
} else {
tweetCheckBox.setVisibility(View.VISIBLE);
}
// Init the toot button if necessary:
Switch tootCheckBox = findViewById(R.id.toot);
tootCheckBox.setChecked(userPrefs.isToot());
if (!userPrefs.isToot()) {
tootCheckBox.setVisibility(View.GONE);
} else {
tootCheckBox.setVisibility(View.VISIBLE);
}
}
/**
* Binds listener for user actions that start any update on a password for the public link
* to the views receiving the user events.
*
* @param shareView Root view in the fragment.
*/
private void initPasswordListener(View shareView) {
mOnPasswordInteractionListener = new OnPasswordInteractionListener();
((Switch) shareView.findViewById(R.id.shareViaLinkPasswordSwitch)).
setOnCheckedChangeListener(mOnPasswordInteractionListener);
shareView.findViewById(R.id.shareViaLinkPasswordLabel).
setOnClickListener(mOnPasswordInteractionListener);
shareView.findViewById(R.id.shareViaLinkPasswordValue).
setOnClickListener(mOnPasswordInteractionListener);
}
/**
* Switch的状态改变监听
*
* @param mSwitch Switch控件
* @param changeListener 事件绑定命令
*/
@BindingAdapter("onCheckedChangeCommand")
public static void onCheckedChangeCommand(final Switch mSwitch, final BindingCommand<Boolean> changeListener) {
if (changeListener != null) {
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changeListener.execute(isChecked);
}
});
}
}
/**
* show Switch Bubble 变色
*
* @param convertView
*/
protected void showBubble_Color(View convertView) {
if (sp_date
.getString("animation" + VALUE, "")
.equals(PropertiesUtils.getAnimationInfo(BaseSet.this)[C.ANIMATION_BUBBLE])) {
TextView title_ = (TextView) convertView
.findViewById(R.id.tv_msseventset_title_);
TextView tip = (TextView) convertView
.findViewById(R.id.tv_msseventset_tip);
Switch sw = (Switch) convertView.findViewById(R.id.sw_msseventset);
title_.setText(R.string.setting_bubble_changeColor);
tip.setText(R.string.tip_bubble_color);
sp_setA = getSharedPreferences(
eventName
+ PropertiesUtils.getAnimationInfo(BaseSet.this)[C.ANIMATION_BUBBLE],
0);
sw.setVisibility(View.VISIBLE);
sw.setChecked(sp_setA.getBoolean("color", true));
sw.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
sp_setA.edit().putBoolean("color", isChecked).commit();
}
});
}
}
private void addSwitch(String name, final SW listner) {
Switch sw = new Switch(this);
sw.setText(name);
sw.setTextColor(Color.WHITE);
//sw.setTextSize(dipToPixels());
sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listner.OnWrite(isChecked);
}
});
patches.addView(sw);
}