能開關開關開關的是開關 ToggleButton
Button都長得差不多,這個的特色就是有個螢光棒,所以還蠻適合當開關用,基礎課程,簡單的介紹一下吧,透過ToggleButton來變更背景吧!
1. 建立專案
2. 加個ToggleButton & relativeLayout指派ID
3. 隨便給的名字吧
4. /res/values/strings.xml
5. Source Code
package   com.example.ex007; import   android.os.Bundle; import   android.app.Activity; import   android.view.Menu; import   android.widget.CompoundButton; import   android.widget.RelativeLayout; import   android.widget.ToggleButton; import   android.widget.CompoundButton.OnCheckedChangeListener; public class MainActivity extends Activity {      private   ToggleButton tb;      private   RelativeLayout rl;      @Override      protected void onCreate(Bundle   savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);          tb = (ToggleButton)   MainActivity.this.findViewById(R.id.toggleButton1);          rl =   (RelativeLayout) MainActivity.this.findViewById(R.id.relativeLayout1);          tb.setOnCheckedChangeListener(new   OnCheckedChangeListener(){               @Override               public void   onCheckedChanged(CompoundButton buttonView,                        boolean isChecked)   {                   // TODO Auto-generated method stub                   if (isChecked) {                        rl.setBackgroundColor(android.graphics.Color.BLACK);                   }   else {                        rl.setBackgroundColor(android.graphics.Color.WHITE);                   };               }          });      }      @Override      public boolean   onCreateOptionsMenu(Menu menu) {          // Inflate the menu; this adds items to the action bar   if it is present.          getMenuInflater().inflate(R.menu.main, menu);          return true;      } }  |   
6. run一下吧,一開始是關
7. 現在是開
就是這麼簡單,isChecked來判斷,明天是Blue Monday,洗洗睡了!!!
範例 : EX007
標籤: ToggleButton






0 個意見:
張貼留言
<< 首頁