要求
按下按钮后在一个新标签中显示输入的姓名和选择的性别

实现


其中对 姓名编辑框进行判空处理
使用getSex方法对sex选择进行一个性别的返回,其返回的String默认为null,并且在没有触发单选的情况下一直为null 所以不用特判空的情况 所以在代码中的sex返回String为未知 无效
在返回sex也是获取其标签的内容,比较灵活
package com.example.ex_2_2;
/**
* @author Dxoca
* @date 2020年3月17日 12:22:20
*/
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
RadioButton boy, girl;
Button insure;
TextView res;
RadioGroup sex;
String res_sex;
public String getSex() {
sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.radioButton_boy)
res_sex = boy.getText().toString();
else if (checkedId == R.id.radioButton_girl)
res_sex = girl.getText().toString();
else
res_sex = "未知";
}
});
return res_sex;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.editText_name);//变量与对象控件关联
boy = findViewById(R.id.radioButton_boy);
girl = findViewById(R.id.radioButton_girl);
insure = findViewById(R.id.button_insure);
res = findViewById(R.id.textView_res);
sex = findViewById(R.id.radioGroup_sex);
insure.setOnClickListener(new View.OnClickListener() {//匿名内部类
@Override
public void onClick(View v) {
res.setText("你输入的信息为:\n姓名:" + (TextUtils.isEmpty(name.getText()) ? "null" : name.getText().toString()) + " 性别:" + getSex());
}
});
}
}
关键
-
android中判断EditText的内容是否为空:
- 两种写法
1.XX.getText().toString()==null
2.XX.getText().toString().equals(null)
但均不能起到任何判断效果,后来通过这种方式实现了,
TextUtils.isEmpty(XX.getText())
- 两种写法
-
按钮的响应匿名内部类写法:
insure.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } });
-
Lambda按钮响应写法:
insure.setOnClickListener((View) -> { res.setText(" "); });
-
单选按钮的响应匿名内部类及选项判断:
sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { } });
本文作者:Author: 寒光博客
文章标题:【Android】单选按钮及编辑框使用练习
本文地址:https://dxoca.cn/StudyNotes/325.html 百度已收录
版权说明:若无注明,本文皆为“Dxoca's blog (寒光博客)”原创,转载请保留文章出处。
本文地址:https://dxoca.cn/StudyNotes/325.html 百度已收录
版权说明:若无注明,本文皆为“Dxoca's blog (寒光博客)”原创,转载请保留文章出处。