Android(安卓)SwitchButton(滑动开关)
16lz
2022-04-18
http://blog.csdn.net/wangjinyu501/article/details/27961303http://blog.csdn.net/wangjinyu501/article/details/27961303
http://blog.csdn.net/wangjinyu501/article/details/27961303
http://blog.csdn.net/wangjinyu501/article/details/27961303
http://blog.csdn.net/wangjinyu501/article/details/27961303
http://blog.csdn.net/wangjinyu501/article/details/27961303
http://blog.csdn.net/wangjinyu501/article/details/27961303
Android SwitchButton(滑动开关)
分类:Android 2014-06-01 12:29 1420人阅读 评论(3) 收藏 举报 版本:1.0 日期:2014.5.172014.6.1 版权:© 2014 kince 转载注明出处在介绍SwitchButton之前,先来看一下系统Button是如何实现的。源码如下: [html] view plain copy
- @RemoteView
- publicclassButtonextendsTextView{
- publicButton(Contextcontext){
- this(context,null);
- }
- publicButton(Contextcontext,AttributeSetattrs){
- this(context,attrs,com.android.internal.R.attr.buttonStyle);
- }
- publicButton(Contextcontext,AttributeSetattrs,intdefStyle){
- super(context,attrs,defStyle);
- }
- @Override
- publicvoidonInitializeAccessibilityEvent(AccessibilityEventevent){
- super.onInitializeAccessibilityEvent(event);
- event.setClassName(Button.class.getName());
- }
- @Override
- publicvoidonInitializeAccessibilityNodeInfo(AccessibilityNodeInfoinfo){
- super.onInitializeAccessibilityNodeInfo(info);
- info.setClassName(Button.class.getName());
- }
- }
直接子类只有有一个,CompoundButton。它是一个抽象类,而实现这个类的控件正是 CheckBox , RadioButton , Switch , ToggleButton 这四个,所以先重点说一下它。源码如下: [html] view plain copy
- /**
- *<p>
- *Abuttonwithtwostates,checkedandunchecked.Whenthebuttonispressed
- *orclicked,thestatechangesautomatically.
- *</p>
- *
- *<p><strong>XMLattributes</strong></p>
- *<p>
- *See{@linkandroid.R.styleable#CompoundButton
- *CompoundButtonAttributes},{@linkandroid.R.styleable#ButtonButton
- *Attributes},{@linkandroid.R.styleable#TextViewTextViewAttributes},{@link
- *android.R.styleable#ViewViewAttributes}
- *</p>
- */
- publicabstractclassCompoundButtonextendsButtonimplementsCheckable{
- privatebooleanmChecked;
- privateintmButtonResource;
- privatebooleanmBroadcasting;
- privateDrawablemButtonDrawable;
- privateOnCheckedChangeListenermOnCheckedChangeListener;
- privateOnCheckedChangeListenermOnCheckedChangeWidgetListener;
- privatestaticfinalint[]CHECKED_STATE_SET={
- R.attr.state_checked
- };
- publicCompoundButton(Contextcontext){
- this(context,null);
- }
- publicCompoundButton(Contextcontext,AttributeSetattrs){
- this(context,attrs,0);
- }
- publicCompoundButton(Contextcontext,AttributeSetattrs,intdefStyle){
- super(context,attrs,defStyle);
- TypedArraya=
- context.obtainStyledAttributes(
- attrs,com.android.internal.R.styleable.CompoundButton,defStyle,0);
- Drawabled=a.getDrawable(com.android.internal.R.styleable.CompoundButton_button);
- if(d!=null){
- setButtonDrawable(d);
- }
- booleanchecked=a
- .getBoolean(com.android.internal.R.styleable.CompoundButton_checked,false);
- setChecked(checked);
- a.recycle();
- }
- publicvoidtoggle(){
- setChecked(!mChecked);
- }
- @Override
- publicbooleanperformClick(){
- /*
- *XXX:Thesearetiny,needsomesurrounding'expandedtoucharea',
- *whichwillneedtobeimplementedinButtonifweonlyoverride
- *performClick()
- */
- /*Whenclicked,togglethestate*/
- toggle();
- returnsuper.performClick();
- }
- @ViewDebug.ExportedProperty
- publicbooleanisChecked(){
- returnmChecked;
- }
- /**
- *<p>Changesthecheckedstateofthisbutton.</p>
- *
- *@paramcheckedtruetocheckthebutton,falsetouncheckit
- */
- publicvoidsetChecked(booleanchecked){
- if(mChecked!=checked){
- mChecked=checked;
- refreshDrawableState();
- notifyViewAccessibilityStateChangedIfNeeded(
- AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
- //AvoidinfiniterecursionsifsetChecked()iscalledfromalistener
- if(mBroadcasting){
- return;
- }
- mBroadcasting=true;
- if(mOnCheckedChangeListener!=null){
- mOnCheckedChangeListener.onCheckedChanged(this,mChecked);
- }
- if(mOnCheckedChangeWidgetListener!=null){
- mOnCheckedChangeWidgetListener.onCheckedChanged(this,mChecked);
- }
- mBroadcasting=false;
- }
- }
- /**
- *Registeracallbacktobeinvokedwhenthecheckedstateofthisbutton
- *changes.
- *
- *@paramlistenerthecallbacktocalloncheckedstatechange
- */
- publicvoidsetOnCheckedChangeListener(OnCheckedChangeListenerlistener){
- mOnCheckedChangeListener=listener;
- }
- /**
- *Registeracallbacktobeinvokedwhenthecheckedstateofthisbutton
- *changes.Thiscallbackisusedforinternalpurposeonly.
- *
- *@paramlistenerthecallbacktocalloncheckedstatechange
- *@hide
- */
- voidsetOnCheckedChangeWidgetListener(OnCheckedChangeListenerlistener){
- mOnCheckedChangeWidgetListener=listener;
- }
- /**
- *Interfacedefinitionforacallbacktobeinvokedwhenthecheckedstate
- *ofacompoundbuttonchanged.
- */
- publicstaticinterfaceOnCheckedChangeListener{
- /**
- *Calledwhenthecheckedstateofacompoundbuttonhaschanged.
- *
- *@parambuttonViewThecompoundbuttonviewwhosestatehaschanged.
- *@paramisCheckedThenewcheckedstateofbuttonView.
- */
- voidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked);
- }
- /**
- *SetthebackgroundtoagivenDrawable,identifiedbyitsresourceid.
- *
- *@paramresidtheresourceidofthedrawabletouseasthebackground
- */
- publicvoidsetButtonDrawable(intresid){
- if(resid!=0&&resid==mButtonResource){
- return;
- }
- mButtonResource=resid;
- Drawabled=null;
- if(mButtonResource!=0){
- d=getResources().getDrawable(mButtonResource);
- }
- setButtonDrawable(d);
- }
- /**
- *SetthebackgroundtoagivenDrawable
- *
- *@paramdTheDrawabletouseasthebackground
- */
- publicvoidsetButtonDrawable(Drawabled){
- if(d!=null){
- if(mButtonDrawable!=null){
- mButtonDrawable.setCallback(null);
- unscheduleDrawable(mButtonDrawable);
- }
- d.setCallback(this);
- d.setVisible(getVisibility()==VISIBLE,false);
- mButtonDrawable=d;
- setMinHeight(mButtonDrawable.getIntrinsicHeight());
- }
- refreshDrawableState();
- }
- @Override
- publicvoidonInitializeAccessibilityEvent(AccessibilityEventevent){
- super.onInitializeAccessibilityEvent(event);
- event.setClassName(CompoundButton.class.getName());
- event.setChecked(mChecked);
- }
- @Override
- publicvoidonInitializeAccessibilityNodeInfo(AccessibilityNodeInfoinfo){
- super.onInitializeAccessibilityNodeInfo(info);
- info.setClassName(CompoundButton.class.getName());
- info.setCheckable(true);
- info.setChecked(mChecked);
- }
- @Override
- publicintgetCompoundPaddingLeft(){
- intpadding=super.getCompoundPaddingLeft();
- if(!isLayoutRtl()){
- finalDrawablebuttonDrawable=mButtonDrawable;
- if(buttonDrawable!=null){
- padding+=buttonDrawable.getIntrinsicWidth();
- }
- }
- returnpadding;
- }
- @Override
- publicintgetCompoundPaddingRight(){
- intpadding=super.getCompoundPaddingRight();
- if(isLayoutRtl()){
- finalDrawablebuttonDrawable=mButtonDrawable;
- if(buttonDrawable!=null){
- padding+=buttonDrawable.getIntrinsicWidth();
- }
- }
- returnpadding;
- }
- /**
- *@hide
- */
- @Override
- publicintgetHorizontalOffsetForDrawables(){
- finalDrawablebuttonDrawable=mButtonDrawable;
- return(buttonDrawable!=null)?buttonDrawable.getIntrinsicWidth():0;
- }
- @Override
- protectedvoidonDraw(Canvascanvas){
- super.onDraw(canvas);
- finalDrawablebuttonDrawable=mButtonDrawable;
- if(buttonDrawable!=null){
- finalintverticalGravity=getGravity()&Gravity.VERTICAL_GRAVITY_MASK;
- finalintdrawableHeight=buttonDrawable.getIntrinsicHeight();
- finalintdrawableWidth=buttonDrawable.getIntrinsicWidth();
- inttop=0;
- switch(verticalGravity){
- caseGravity.BOTTOM:
- top=getHeight()-drawableHeight;
- break;
- caseGravity.CENTER_VERTICAL:
- top=(getHeight()-drawableHeight)/2;
- break;
- }
- intbottom=top+drawableHeight;
- intleft=isLayoutRtl()?getWidth()-drawableWidth:0;
- intright=isLayoutRtl()?getWidth():drawableWidth;
- buttonDrawable.setBounds(left,top,right,bottom);
- buttonDrawable.draw(canvas);
- }
- }
- @Override
- protectedint[]onCreateDrawableState(intextraSpace){
- finalint[]drawableState=super.onCreateDrawableState(extraSpace+1);
- if(isChecked()){
- mergeDrawableStates(drawableState,CHECKED_STATE_SET);
- }
- returndrawableState;
- }
- @Override
- protectedvoiddrawableStateChanged(){
- super.drawableStateChanged();
- if(mButtonDrawable!=null){
- int[]myDrawableState=getDrawableState();
- //SetthestateoftheDrawable
- mButtonDrawable.setState(myDrawableState);
- invalidate();
- }
- }
- @Override
- protectedbooleanverifyDrawable(Drawablewho){
- returnsuper.verifyDrawable(who)||who==mButtonDrawable;
- }
- @Override
- publicvoidjumpDrawablesToCurrentState(){
- super.jumpDrawablesToCurrentState();
- if(mButtonDrawable!=null)mButtonDrawable.jumpToCurrentState();
- }
- staticclassSavedStateextendsBaseSavedState{
- booleanchecked;
- /**
- *Constructorcalledfrom{@linkCompoundButton#onSaveInstanceState()}
- */
- SavedState(ParcelablesuperState){
- super(superState);
- }
- /**
- *Constructorcalledfrom{@link#CREATOR}
- */
- privateSavedState(Parcelin){
- super(in);
- checked=(Boolean)in.readValue(null);
- }
- @Override
- publicvoidwriteToParcel(Parcelout,intflags){
- super.writeToParcel(out,flags);
- out.writeValue(checked);
- }
- @Override
- publicStringtoString(){
- return"CompoundButton.SavedState{"
- +Integer.toHexString(System.identityHashCode(this))
- +"checked="+checked+"}";
- }
- publicstaticfinalParcelable.Creator<SavedState>CREATOR
- =newParcelable.Creator<SavedState>(){
- publicSavedStatecreateFromParcel(Parcelin){
- returnnewSavedState(in);
- }
- publicSavedState[]newArray(intsize){
- returnnewSavedState[size];
- }
- };
- }
- @Override
- publicParcelableonSaveInstanceState(){
- //Forceourancestorclasstosaveitsstate
- setFreezesText(true);
- ParcelablesuperState=super.onSaveInstanceState();
- SavedStatess=newSavedState(superState);
- ss.checked=isChecked();
- returnss;
- }
- @Override
- publicvoidonRestoreInstanceState(Parcelablestate){
- SavedStatess=(SavedState)state;
- super.onRestoreInstanceState(ss.getSuperState());
- setChecked(ss.checked);
- requestLayout();
- }
- }
- publicCompoundButton(Contextcontext,AttributeSetattrs,intdefStyle){
- super(context,attrs,defStyle);
- TypedArraya=
- context.obtainStyledAttributes(
- attrs,com.android.internal.R.styleable.CompoundButton,defStyle,0);
- Drawabled=a.getDrawable(com.android.internal.R.styleable.CompoundButton_button);
- if(d!=null){
- setButtonDrawable(d);
- }
- booleanchecked=a
- .getBoolean(com.android.internal.R.styleable.CompoundButton_checked,false);
- setChecked(checked);
- a.recycle();
- }
- /**
- *SetthebackgroundtoagivenDrawable
- *
- *@paramdTheDrawabletouseasthebackground
- */
- publicvoidsetButtonDrawable(Drawabled){
- if(d!=null){
- if(mButtonDrawable!=null){
- mButtonDrawable.setCallback(null);
- unscheduleDrawable(mButtonDrawable);
- }
- d.setCallback(this);
- d.setVisible(getVisibility()==VISIBLE,false);
- mButtonDrawable=d;
- setMinHeight(mButtonDrawable.getIntrinsicHeight());
- }
- refreshDrawableState();
- }
- /**
- *UnscheduleanyeventsassociatedwiththegivenDrawable.Thiscanbe
- *usedwhenselectinganewDrawableintoaview,sothattheprevious
- *oneiscompletelyunscheduled.
- *
- *@paramwhoTheDrawabletounschedule.
- *
- *@see#drawableStateChanged
- */
- publicvoidunscheduleDrawable(Drawablewho){
- if(mAttachInfo!=null&&who!=null){
- mAttachInfo.mViewRootImpl.mChoreographer.removeCallbacks(
- Choreographer.CALLBACK_ANIMATION,null,who);
- }
- }
- /**
- *<p>Changesthecheckedstateofthisbutton.</p>
- *
- *@paramcheckedtruetocheckthebutton,falsetouncheckit
- */
- publicvoidsetChecked(booleanchecked){
- if(mChecked!=checked){
- mChecked=checked;
- refreshDrawableState();
- notifyViewAccessibilityStateChangedIfNeeded(
- AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED);
- //AvoidinfiniterecursionsifsetChecked()iscalledfromalistener
- if(mBroadcasting){
- return;
- }
- mBroadcasting=true;
- if(mOnCheckedChangeListener!=null){
- mOnCheckedChangeListener.onCheckedChanged(this,mChecked);
- }
- if(mOnCheckedChangeWidgetListener!=null){
- mOnCheckedChangeWidgetListener.onCheckedChanged(this,mChecked);
- }
- mBroadcasting=false;
- }
- }
- /**
- *Interfacedefinitionforacallbacktobeinvokedwhenthecheckedstate
- *ofacompoundbuttonchanged.
- */
- publicstaticinterfaceOnCheckedChangeListener{
- /**
- *Calledwhenthecheckedstateofacompoundbuttonhaschanged.
- *
- *@parambuttonViewThecompoundbuttonviewwhosestatehaschanged.
- *@paramisCheckedThenewcheckedstateofbuttonView.
- */
- voidonCheckedChanged(CompoundButtonbuttonView,booleanisChecked);
- }
- @Override
- protectedvoidonDraw(Canvascanvas){
- super.onDraw(canvas);
- finalDrawablebuttonDrawable=mButtonDrawable;
- if(buttonDrawable!=null){
- finalintverticalGravity=getGravity()&Gravity.VERTICAL_GRAVITY_MASK;
- finalintdrawableHeight=buttonDrawable.getIntrinsicHeight();
- finalintdrawableWidth=buttonDrawable.getIntrinsicWidth();
- inttop=0;
- switch(verticalGravity){
- caseGravity.BOTTOM:
- top=getHeight()-drawableHeight;
- break;
- caseGravity.CENTER_VERTICAL:
- top=(getHeight()-drawableHeight)/2;
- break;
- }
- intbottom=top+drawableHeight;
- intleft=isLayoutRtl()?getWidth()-drawableWidth:0;
- intright=isLayoutRtl()?getWidth():drawableWidth;
- buttonDrawable.setBounds(left,top,right,bottom);
- buttonDrawable.draw(canvas);
- }
- }
1、CheckBox [html] view plain copy
- publicclassCheckBoxextendsCompoundButton{
- publicCheckBox(Contextcontext){
- this(context,null);
- }
- publicCheckBox(Contextcontext,AttributeSetattrs){
- this(context,attrs,com.android.internal.R.attr.checkboxStyle);
- }
- publicCheckBox(Contextcontext,AttributeSetattrs,intdefStyle){
- super(context,attrs,defStyle);
- }
- @Override
- publicvoidonInitializeAccessibilityEvent(AccessibilityEventevent){
- super.onInitializeAccessibilityEvent(event);
- event.setClassName(CheckBox.class.getName());
- }
- @Override
- publicvoidonInitializeAccessibilityNodeInfo(AccessibilityNodeInfoinfo){
- super.onInitializeAccessibilityNodeInfo(info);
- info.setClassName(CheckBox.class.getName());
- }
- }
- publicclassRadioButtonextendsCompoundButton{
- publicRadioButton(Contextcontext){
- this(context,null);
- }
- publicRadioButton(Contextcontext,AttributeSetattrs){
- this(context,attrs,com.android.internal.R.attr.radioButtonStyle);
- }
- publicRadioButton(Contextcontext,AttributeSetattrs,intdefStyle){
- super(context,attrs,defStyle);
- }
- /**
- *{@inheritDoc}
- *<p>
- *Iftheradiobuttonisalreadychecked,thismethodwillnottoggletheradiobutton.
- */
- @Override
- publicvoidtoggle(){
- //weoverridetopreventtogglewhentheradioisalready
- //checked(asopposedtocheckboxeswidgets)
- if(!isChecked()){
- super.toggle();
- }
- }
- @Override
- publicvoidonInitializeAccessibilityEvent(AccessibilityEventevent){
- super.onInitializeAccessibilityEvent(event);
- event.setClassName(RadioButton.class.getName());
- }
- @Override
- publicvoidonInitializeAccessibilityNodeInfo(AccessibilityNodeInfoinfo){
- super.onInitializeAccessibilityNodeInfo(info);
- info.setClassName(RadioButton.class.getName());
- }
- }
如图1-3,在实现的时候,先画一个开关背景图片只,然后在其上面画一个按钮,滑动开关的时候对上面的按钮进行处理即可。 准备: 1、按钮图片
2、背景图片 编码: 在自定义滑动按钮控件的时候,可以有多种选择,可以继承于Button,也可以继承于Button的子类,也可以继承于View类等。我们知道滑动按钮是一个很简单的控件,就是左右滑动改变显示内容,不需要其他的额外东西在里面,所以直接继承于View来实现即可。如果继承于系统的一些控件,那么有很多东西用不到,会造成浪费。 1、定义一个类继承于View,初始化构造方法,在构造方法中加载图片及其信息。 2、重写onMeasure()方法,计算控件的大小。 3、重写onTouchEvent()方法,对滑动事件进行判别处理。 4、定义接口,实现回调。 5、重写onDraw()方法,动态画出按钮。 代码如下: [html] view plain copy
- /**
- *
- */
- packagecom.kince.slidebutton;
- importandroid.content.Context;
- importandroid.graphics.Bitmap;
- importandroid.graphics.BitmapFactory;
- importandroid.graphics.Canvas;
- importandroid.util.AttributeSet;
- importandroid.util.Log;
- importandroid.view.MotionEvent;
- importandroid.view.View;
- /**
- *@authorkince
- *@category左右手势滑动button
- *@serial1.0.0
- *@since2014.5.17
- *@seehttp://blog.csdn.net/wangjinyu501
- *
- */
- publicclassSlideButtonextendsView{
- privateBitmapslideBitMap;//滑动图片
- privateBitmapswitchBitMap;//背景图片
- privateintslideBitMapWidth;//滑动图片宽度
- privateintswitchBitMapWidth;//背景图片宽度
- privateintswitchBitMapHeight;//背景图片高度
- privatebooleancurrentState;//开关状态
- privatebooleanisSliding=false;//是否正在滑动中
- privateintcurrentX;//当前开关的位置
- privateOnToggleStateChangedListenermChangedListener;//回调接口
- /**
- *@paramcontext
- *在java代码中直接调用使用此构造方法
- */
- publicSlideButton(Contextcontext){
- this(context,null);
- //TODOAuto-generatedconstructorstub
- }
- /**
- *@paramcontext
- *@paramattrs
- *在xml中使用要用到这个方法
- */
- publicSlideButton(Contextcontext,AttributeSetattrs){
- this(context,attrs,0);
- //TODOAuto-generatedconstructorstub
- }
- /**
- *@paramcontext
- *@paramattrs
- *@paramdefStyleAttr
- *指定一个样式
- */
- publicSlideButton(Contextcontext,AttributeSetattrs,intdefStyleAttr){
- super(context,attrs,defStyleAttr);
- initBitmap();
- }
- /**
- *@category加载背景图片以及开关图片然后获取各自的宽高
- *
- */
- privatevoidinitBitmap(){
- //TODOAuto-generatedmethodstub
- slideBitMap=BitmapFactory.decodeResource(getResources(),
- R.drawable.slide_button_background);
- switchBitMap=BitmapFactory.decodeResource(getResources(),
- R.drawable.switch_background);
- slideBitMapWidth=slideBitMap.getWidth();
- switchBitMapWidth=switchBitMap.getWidth();
- switchBitMapHeight=switchBitMap.getHeight();
- Log.i("switchBitMapWidth",switchBitMapWidth+"");
- }
- @Override
- protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){
- //TODOAuto-generatedmethodstub
- super.onMeasure(widthMeasureSpec,heightMeasureSpec);
- setMeasuredDimension(switchBitMapWidth,switchBitMapHeight);//设置控件的宽高
- }
- @Override
- protectedvoidonDraw(Canvascanvas){
- //绘制button背景图片
- canvas.drawBitmap(switchBitMap,0,0,null);
- //绘制滑动开关
- if(isSliding){//如果当前状态是滑动中则动态绘制开关
- intdis=currentX-slideBitMapWidth/2;
- if(dis<0){
- dis=0;
- }elseif(dis>switchBitMapWidth-slideBitMapWidth){
- dis=switchBitMapWidth-slideBitMapWidth;
- }
- canvas.drawBitmap(slideBitMap,dis,0,null);
- }else{
- if(currentState){//绘制开关为开的状态
- canvas.drawBitmap(slideBitMap,switchBitMapWidth
- -slideBitMapWidth,0,null);
- }else{//绘制开关为关的状态
- canvas.drawBitmap(slideBitMap,0,0,null);
- }
- }
- super.onDraw(canvas);
- }
- @Override
- publicbooleanonTouchEvent(MotionEventevent){
- //手势识别判断滑动方向
- intaction=event.getAction();
- switch(action){
- caseMotionEvent.ACTION_DOWN:
- isSliding=true;
- currentX=(int)event.getX();
- break;
- caseMotionEvent.ACTION_MOVE:
- currentX=(int)event.getX();
- Log.i("currentX",currentX+"");
- break;
- caseMotionEvent.ACTION_UP:
- isSliding=false;
- intbgCenter=switchBitMapWidth/2;
- booleanstate=currentX>bgCenter;//改变后的状态
- if(state!=currentState&&mChangedListener!=null){//添加回调
- mChangedListener.onToggleStateChanged(state);
- }
- currentState=state;
- break;
- default:
- break;
- }
- invalidate();
- returntrue;
- }
- publicOnToggleStateChangedListenergetmChangedListener(){
- returnmChangedListener;
- }
- publicvoidsetmChangedListener(
- OnToggleStateChangedListenermChangedListener){
- this.mChangedListener=mChangedListener;
- }
- publicbooleanisToggleState(){
- returncurrentState;
- }
- publicvoidsetToggleState(booleancurrentState){
- this.currentState=currentState;
- }
- }
- packagecom.kince.slidebutton;
- **
- *@authorkince
- *
- */
- ublicinterfaceOnToggleStateChangedListener{
- /**
- *@category
- *@paramstate
- */
- publicvoidonToggleStateChanged(booleanstate);
- packagecom.kince.slidebutton;
- importandroid.support.v7.app.ActionBarActivity;
- importandroid.support.v7.app.ActionBar;
- importandroid.support.v4.app.Fragment;
- importandroid.support.v4.app.FragmentActivity;
- importandroid.os.Bundle;
- importandroid.view.LayoutInflater;
- importandroid.view.Menu;
- importandroid.view.MenuItem;
- importandroid.view.View;
- importandroid.view.ViewGroup;
- importandroid.widget.Toast;
- importandroid.os.Build;
- publicclassMainActivityextendsActionBarActivity{
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- if(savedInstanceState==null){
- getSupportFragmentManager().beginTransaction()
- .add(R.id.container,newPlaceholderFragment()).commit();
- }
- }
- @Override
- publicbooleanonCreateOptionsMenu(Menumenu){
- //Inflatethemenu;thisaddsitemstotheactionbarifitispresent.
- getMenuInflater().inflate(R.menu.main,menu);
- returntrue;
- }
- @Override
- publicbooleanonOptionsItemSelected(MenuItemitem){
- //Handleactionbaritemclickshere.Theactionbarwill
- //automaticallyhandleclicksontheHome/Upbutton,solong
- //asyouspecifyaparentactivityinAndroidManifest.xml.
- intid=item.getItemId();
- if(id==R.id.action_settings){
- returntrue;
- }
- returnsuper.onOptionsItemSelected(item);
- }
- /**
- *Aplaceholderfragmentcontainingasimpleview.
- */
- publicstaticclassPlaceholderFragmentextendsFragmentimplements
- OnToggleStateChangedListener{
- privateSlideButtonslidebutton;
- publicPlaceholderFragment(){
- }
- @Override
- publicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,
- BundlesavedInstanceState){
- ViewrootView=inflater.inflate(R.layout.fragment_main,container,
- false);
- slidebutton=(SlideButton)rootView.findViewById(R.id.slidebutton1);
- //设置一下开关的状态
- slidebutton.setToggleState(true);//设置开关的状态为打开
- slidebutton.setmChangedListener(this);
- returnrootView;
- }
- @Override
- publicvoidonToggleStateChanged(booleanstate){
- //TODOAuto-generatedmethodstub
- FragmentActivityactivity=getActivity();
- if(state){
- Toast.makeText(activity,"开关打开",0).show();
- }else{
- Toast.makeText(activity,"开关关闭",0).show();
- }
- }
- }
- }
更多相关文章
- ViewFlipper
- Android(安卓)各种音量的获取和设置
- Android学习笔记----Android简单有效的闪屏制作
- android 获取IP
- Android(安卓)onSaveInstanceState和onRestoreInstanceState触发
- Android(安卓)判断 app 是否安装的方法 (native.js)
- android EditText 只能输入无法删除的解决方法
- 浅谈Java中Collections.sort对List排序的两种方法
- Python list sort方法的具体使用