You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio Java Button点击校验输入值实现页面跳转

Java版Android输入校验跳转实现方案

修改步骤

  • 首先确认activity_main.xml布局中已添加EditText输入控件,为控件设置id为et_education,确保布局中Button的id和现有代码中R.id.button保持一致。

布局中EditText控件参考代码:

<EditText
    android:id="@+id/et_education"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="请输入学历等级"/>
  • 在MainActivity类中补充EditText控件的成员变量声明,在onCreate方法中完成输入控件的绑定
  • 替换onClick方法中写死的check标识逻辑:点击按钮时先获取输入框的文本内容,去除首尾空格后和三个指定合法值做匹配,根据匹配结果动态设置check的值,后续的Toast提示、页面跳转逻辑无需改动即可正常运行
  • 提前确认Activity2已在AndroidManifest.xml文件中完成注册,否则跳转时会触发Activity未注册的崩溃问题

补全后完整代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button;
    // 补充输入控件成员变量声明
    private EditText etEducation;
    private int check = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = findViewById(R.id.button);
        // 绑定输入控件
        etEducation = findViewById(R.id.et_education);
        button.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        // Check for valid education
        // 获取输入内容,去除首尾空白字符,避免用户误输入空格导致校验失败
        String input = etEducation.getText().toString().trim();
        // 先默认校验不通过
        check = 0;
        // 匹配三个合法值,用常量调用equals避免空指针
        if ("Primary".equals(input) || "Secondary".equals(input) || "Higher".equals(input)) {
            check = 1;
        }

        // if yes -> next view
        if (check == 0 ) {
            Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
        } else if ( check == 1) {
            startActivity(new Intent(this, Activity2.class));
        }
    }
}

可选优化

  • 如果需要支持大小写不敏感校验(比如用户输入primary、PRIMARY也能通过),可以将输入内容统一转为小写/大写后再做比对,示例判断逻辑:
String inputLower = input.toLowerCase();
if ("primary".equals(inputLower) || "secondary".equals(inputLower) || "higher".equals(inputLower)) {
    check = 1;
}
  • 可以在strings.xml中给error字符串设置更明确的提示内容,例如输入无效,请输入Primary、Secondary、Higher三个值中的一个,方便用户明确错误原因。

内容的提问来源于stack exchange,提问作者androidjunior

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 01:06:22