我正在使用片段刪除應用程序。我的問題是當我按下後退按鈕,從任何屏幕,應用程序關閉。應用程序顯示預期的佈局,但立即關閉。這是我的片段的代碼,他包含一個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語句並解決您的問題。 –