Android 关注空字段并显示Toast,并停留在其当前片段上
我有一个活动和两个片段。在我的第一个片段中,它有一个用户名和密码EditText和一个提交按钮。我想把重点放在字段上,当字段为空时,我想显示一个toast,它将停留在LoginFragment上,显示toast,而不继续我的主要活动。但目前,当我点击submit按钮时,它会显示toast,但会转到我的MainActivityAndroid 关注空字段并显示Toast,并停留在其当前片段上,android,android-activity,fragment,toast,Android,Android Activity,Fragment,Toast,我有一个活动和两个片段。在我的第一个片段中,它有一个用户名和密码EditText和一个提交按钮。我想把重点放在字段上,当字段为空时,我想显示一个toast,它将停留在LoginFragment上,显示toast,而不继续我的主要活动。但目前,当我点击submit按钮时,它会显示toast,但会转到我的MainActivity public void onClick(View v) { Intent i; Context context = getActivity().getA
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 frag = new Fragment();
到
你为什么在交换机中呼叫暂停?我以为这样做的目的是保持在当前屏幕上?我认为当使用onPause时,它将保持在片段上。很抱歉,我不知道什么时候可以使用它。当您的活动离开前台/不在屏幕上时,Android会呼叫暂停。你不需要叫它,除非有你想跑的行为。我明白了。谢谢我删除了onPause,但仍然转到我的主要活动。我该怎么办?为什么在检查密码字段时调用getActivity?
Fragment frag = null;