今天开始学习Android用户界面各个组件,做了个Demo,Android包括布局等界面设置都放置在xml文件中,然后再OnCreate方法中为按钮等组件分别添加事件即可,其开发模式有点类似JavaScript,很容易上手。如下图:
其核心代码如下:
public class AndroidView extends Activity {
private RadioGroup radioGroup;
private RadioButton rb1;
private RadioButton rb2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radioGroup = (RadioGroup) this.findViewById(R.id.m_radioGroup);//获取组件
rb1 = (RadioButton) this.findViewById(R.id.m_radioButton1);
rb2 = (RadioButton) this.findViewById(R.id.m_radioButton2);
//为组件注册事件
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == rb1.getId()){
alert("回答正确!");
}else{
alert("回答错误!正确答案是:"+rb1.getText());
}
}
});
}
//输出信息
public void alert(String str){
//this是当前页面显示
Toast toast = Toast.makeText(this, str, Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 0, 160);//显示位置
toast.show();
}
}