专注于空白字段并显示 Toast 并停留在其当前 Fragment

Focus on empty field and display Toast and stays on its current Fragment

我有一个activity和两个片段。在我的第一个片段中,它有一个用户名和密码 EditText 以及一个提交按钮。我想专注于该字段,当它为空时,我想显示祝酒词,它将保留在显示祝酒词的 LoginFragment 上,不会继续执行我的 MainActivity。但是目前,当我单击提交按钮时,它会显示祝酒词,但会转到我的 MainActivity。

 public void onClick(View v) {
    Intent i;

    Context context = getActivity().getApplicationContext();
    CharSequence text = getResources().getString(R.string.required_both);
    int duration = Toast.LENGTH_SHORT;

    Toast toast = Toast.makeText(context, text, duration);

Fragment frag = new Fragment();

    switch(v.getId()) {
        case R.id.btn_submit:

            if(et_username.getText().toString().isEmpty()) {
                et_username.requestFocus();
                toast.makeText(context, "Please enter your Username", Toast.LENGTH_SHORT).show();
              } else if (et_password.getText().toString().isEmpty()) {
                et_password.requestFocus();
                toast.makeText(context, "Please enter your Password", Toast.LENGTH_SHORT).show();
            }else if(et_username.getText().toString().isEmpty() && et_password.getText().toString().isEmpty()){
                toast.makeText(context, "Please enter your Username and Password", Toast.LENGTH_SHORT).show();
            }else if(spn_status.getSelectedItem().toString().equals("As Employee")  &&
                    !et_username.getText().toString().isEmpty()
                        && !et_password.getText().toString().isEmpty()){

                    mCallback.onLogin("employee");

                    frag = new HomeEmployeeFragment();

            }else if(spn_status.getSelectedItem().toString().equals("As Employer")  &&
                    !et_username.getText().toString().isEmpty()
                            && !et_password.getText().toString().isEmpty()){

                    mCallback.onLogin("employer");
                    frag = new HomeEmployerFragment();
            }
            break;
    }


    if (frag != null ) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, frag).commit();


    } else {
        // error in creating fragment
        Log.e("LoginFragment", "Error in creating fragment");
    }
}

有人可以帮帮我吗?我还是 android 的新手。谢谢。

尝试将 frag 初始化为 null 而不是新的 Fragment。这样,您就不会在按下按钮时执行片段事务。所以改变:

 Fragment frag = new Fragment();

 Fragment frag = null;