Android 第十一課——UI Checkbox

經常使用基礎空組件html

6 CheckBoxjava

複選框是經常使用組件之一,可是開發過程當中雖然不少地方會用到複選框,可是卻不會用Android系統提供的原始樣式,相似咱們在寫html時,不一樣的瀏覽器提供的複選框按鈕是不同的,兼容性也不好,通常用圖片替代假裝。可是不管如何假裝樣式,複選框的功能都是同樣的。android

layout中組件:瀏覽器

       <CheckBox  
            android:id="@+id/cb1" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:checked="true" 
            android:text="basketball"/> 
        <CheckBox  
            android:id="@+id/cb2" 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:text="baseball"/>

Activity中組件:ide

   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // 獲取checkbox
        cb1 = (CheckBox)findViewById(R.id.cb1);
        cb2 = (CheckBox)findViewById(R.id.cb2);
        // 爲checkbox註冊事件監聽(當複選框被選中或從選中到未被選中狀態時這個類的onCheckedChanged方法被觸發)
        CBCheckedImpl impl = new CBCheckedImpl();
        cb1.setOnCheckedChangeListener(impl);
        cb2.setOnCheckedChangeListener(impl);
    }
     
  // Activity內部類,實現android.widget.CompoundButton.OnCheckedChangeListener接口同時實現onCheckedChanged方法
  btn表示發生狀態變化的組件,flag若是爲true表示選中,不然表示爲被選中
  @Override 
  public void onCheckedChanged(CompoundButton btn, boolean flag) { 
   // TODO Auto-generated method stub 
   String rs = "nothing"; 
   rs = flag?"選中了"+btn.getText().toString():"未選中"+btn.getText().toString(); 
   Toast.makeText(CheckBoxActivity.this,rs, Toast.LENGTH_SHORT).show(); 
  } 
    
         
  }

注意:學習

1)複選框的使用基本和單選按鈕差很少,主要就是要記住單選按鈕實現的接口監聽是android.widget.RadioGroup.OnCheckedChangeListener;然而複習按鈕實現的監聽是android.widget.CompoundButton.OnCheckedChangeListener。不要覺得單選按鈕和複選按鈕都是CompoundButton的子類,就應該實現相同的接口,其實是由於,單選按鈕有組的概念,然而複選按鈕沒有組的概念。this


下一節將學習UI的spa

7 ProgressBarcode

8 ListView ListActivity SimpleAdapterorm

相關文章
相關標籤/搜索