Button、CheckBox、RadioGroup
Button
监听单击Button
public class MainActivity extends Activity implements OnClickListener { private Button bt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt = (Button) findViewById(R.id.bt); bt.setOnClickListener(this); } public void onClick(View v) { bt.setText("you have clicked!"); } }
CheckBox
CheckBox是从CompoundButton中继承的,而CompoundButton是继承TextView。
public class MainActivity extends Activity implements CompoundButton.OnCheckedChangeListener { private CheckBox cb; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cb = (CheckBox) findViewById(R.id.cb); cb.setOnCheckedChangeListener(this); } public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { cb.setText("This checkbox is : " + (isChecked ? "checked" : "unchcked")); } }
RadioGroup,常见的方法包括有check(),例如roup.check(R.id.radio1)),将R.id.radio1对应的radiobutton选上;clearCheck(),清楚所有的选择,全部都是unchecked;getCheckedRadioButtonId(),获取选上的radiobutton的ID,无则返回-1。
public class MainActivity extends Activity implements RadioGroup.OnCheckedChangeListener { private RadioGroup rg; private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); rg = (RadioGroup) findViewById(R.id.rg); tv = (TextView) findViewById(R.id.tv); rg.setOnCheckedChangeListener(this); } public void onCheckedChanged(RadioGroup group, int checkedId) { int radioId = rg.getCheckedRadioButtonId(); if (radioId < 0) tv.setText("No Radio Button is selected"); else { RadioButton rb = (RadioButton) group.findViewById(radioId); tv.setText("radio button: " + rb.getText() + " is selected"); } } }