安卓使用之常见事件或动作
所有组件可使用的点击事件
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = etName.getText().toString();
Toast.makeText(MainActivity.this,name,Toast.LENGTH_SHORT).show();
}
});
开关,更换背景颜色
aSwitch = findViewById(R.id.switch1);
screenLayout =findViewById(R.id.screenLayout);
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
screenLayout.setBackgroundColor(Color.BLACK);
}else{
screenLayout.setBackgroundColor(Color.WHITE);
}
}
});
复选框,监听取消和选中
checkBox2 =findViewById(R.id.checkBox2);
checkBox2.setOnCheckedChangeListener(
new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
Toast.makeText(MainActivity.this,b?"选中"+checkBox2.getText():"取消"+checkBox2.getText(),Toast.LENGTH_SHORT).show();
if(b){
resMap.put("c1",checkBox2.getText().toString());
}else {
resMap.remove("c1");
}
}
});
单选按钮,更换控件图片
radioGroup = findViewById(R.id.myRadioGroup);
radioGroup.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.radioButton){
imageView.setImageResource(R.drawable.apple_logo_black_svg);
}else{
imageView.setImageResource(R.drawable.android_robot_svg);
}
}
});
星星评价
ratingBar = findViewById(R.id.ratingBar);
ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
textView2.setText(v*20+"%");
}
});
其他动作:
对话框:
Toast.makeText(EventCont.this,"已经没有题目了",Toast.LENGTH_SHORT).show();
获取TextView内容:
String name = etName.getText().toString();
设置TextView内容:
tv2.setText(String.valueOf(totalScore));
设置按钮禁用:
btn.setEnabled(false);