专注于空场并显示Toast并保持其当前片段

时间:2015-04-20 01:18:44

标签: android android-activity fragment toast

我有一个活动和两个片段。在我的第一个片段中,它有一个用户名和密码EditText和一个提交按钮。我想专注于该领域,当它是空的时我想表示敬酒,它将保留在LoginFragment上,其中显示toast并且不会进入我的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新手。谢谢。

1 个答案:

答案 0 :(得分:0)

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

 Fragment frag = new Fragment();

 Fragment frag = null;