从父活动更新片段

时间:2015-09-27 18:35:54

标签: java android android-fragments

我有一个片段在父活动中执行一个方法,然后如果条件合适,父活动应该更新片段。但是当我这样做时我得到了这个错误:

 java.lang.IllegalStateException: Fragment LoginFragment{426ebc40} not attached to Activity
            at android.support.v4.app.Fragment.getResources(Fragment.java:620)
            at com.myapp.fragments.LoginFragment.setLoginFailed(LoginFragment.java:184)
            at com.myapp.activities.WelcomeActivity$7$1.run(WelcomeActivity.java:357)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5602)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

以下是父活动的代码:

 runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mSocket.off();
                            mSocket.disconnect();
//this call causes the crash
                            loginFragment.setLoginFailed();
                        }
                    });

以下是我如何从父活动中启动片段:

public void showLoginFragment(String carrierName, ArrayList<CheckOperator> supportedCarriers, boolean carrierIsSupported) {
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.setCustomAnimations(R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_top, R.anim.abc_slide_in_top, R.anim.abc_slide_out_bottom);
        Bundle b = new Bundle();
        b.putSerializable(IntentConstants.OPERATORS, supportedCarriers);
        b.putString(IntentConstants.OPERATOR_NAME, carrierName);
        b.putBoolean(IntentConstants.OPERATOR_SUPPORTED, carrierIsSupported);
        b.putString(IntentConstants.TOKEN, token);
        b.putString(IntentConstants.MMAIL, mMail);
        loginFragment.setArguments(b);
        ft.replace(R.id.welcome_fragment_container, loginFragment, "login");
        ft.commit();

        writePrefs().putString(Constants.CARRIER_NAME, carrierName).apply();
    }

以下是片段中的代码:

  public void setLoginFailed() {
        weNeedTxt.setTextColor(getResources().getColor(R.color.error_color));
        weNeedTxt.setText(getString(R.string.user_pass_error));
    }

任何人都可以帮我解决这个问题吗?感谢

0 个答案:

没有答案