我正在使用片段删除应用程序。我的问题是当我按下后退按钮,从任何屏幕,应用程序关闭。应用程序显示预期的布局,但立即关闭。这是我的片段的代码,他包含一个Button。onBackPressed Android片段
public class LoginFragment extends android.support.v4.app.Fragment implements View.OnClickListener, OnBackPressed{
private StatusFragment.StatusListener statusListener;
public static LoginFragment newInstance() {return new LoginFragment();}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_login, container, false); //este fragment_profile se muestra
Button go_login=(Button)layout.findViewById(R.id.button_gologin);
go_login.setOnClickListener(this);
Button go_registration=(Button)layout.findViewById(R.id.button_goregistration);
go_registration.setOnClickListener(this);
return layout;
}
@Override
public void onBackPressed() {
//on Back Pressed
}
@Override
public void onDetach() {
super.onDetach();
statusListener = null;
}
@Override
public void onClick(View v)
{
switch (v.getId()){
case R.id.button_gologin:{
Model model=(Model)getActivity().getApplicationContext();
EditText text_log = (EditText)getActivity().findViewById(R.id.editText_user);
EditText text_pass = (EditText)getActivity().findViewById(R.id.editText_pass);
model.sendLogin(text_log.getText().toString(),text_pass.getText().toString());
model.isPasswordCorrect();
break;
}
然后我们在MainActivity
public class MainActivity extends FragmentActivity implements AccountFragment.OnFragmentInteractionListener,
StatusFragment.StatusListener, ObserverModel {
}
private void showLogin() {
LoginFragment fragment = (LoginFragment) fragmentManager.findFragmentByTag(LOGIN_FRAGMENT);
if (fragment == null) {
Log.d(TAG, "Открываем статус");
} else {
Log.d(TAG, "Статус открыт");
}
android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, loginFragment, LOGIN_FRAGMENT).addToBackStack(STATUS);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
transaction.addToBackStack(null);
transaction.commit();
}
@Override
public void onBackPressed() {
Fragment currentFragment = getSupportFragmentManager().getFragments().get(getSupportFragmentManager().getBackStackEntryCount() - 1);
if (currentFragment instanceof OnBackPressed) {
((OnBackPressed) currentFragment).onBackPressed();
} else {
super.onBackPressed();
}
}
问题出在哪里?我正在阅读其他人的帖子,但找不到解决方案。由于
我觉得这行有一些问题===> transaction.replace(R.id.container,loginFragment,LOGIN_FRAGMENT).addToBackStack(STATUS);你在哪里定义了“loginFragment”?纠正我,如果我错了! – Darsh
公共类MainActivity扩展FragmentActivity实现AccountFragment.OnFragmentInteractionListener, StatusFragment.StatusListener,ObserverModel {0} {0}}}}}}}}}}}} LoginFragment loginFragment = new LoginFragment()final static String LOGIN_FRAGMENT =“Login”; – baldcl
在FragmentActivity中添加super.onBackPressed到else语句并解决您的问题。 –