如何从android中的非活动类调用片段

时间:2016-03-30 07:42:28

标签: android android-fragments android-activity

我有一个登录Fragment和一个名为 CServerResponse 的类。

我想从LoginFragment班级致电CServerResponse

我该怎么做?

以下是CServerResponse类代码:

public class CServerResponse {
    public static CServerResponse s_m_oServerResponse;
    public Context m_Context;

    private CServerResponse(Context m_Context) {
        this.m_Context = m_Context;
    }

    public static CServerResponse getInstance() {
        if (s_m_oServerResponse == null) {
            s_m_oServerResponse = new CServerResponse();
        }
        return s_m_oServerResponse;
    }

    public void getLoginResponse() throws JSONException {
        final Fragment activity = (Fragment) m_Context;
        if (CLoginScreen.m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {

            CLoginScreen.m_oLoginSession.setLoginData(
                CLoginScreen.s_szResponseMobile, CLoginScreen.s_szResponsePassword);

            getActivity().getSupportFragmentManager()
                         .beginTransaction()
                         .replace(R.id.container, new CDealMainListing()).commit();

            CToastMessage.getInstance().showToast(getActivity(), "You are successfully Logged In");

        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {

            CToastMessage.getInstance().showToast(getActivity(), "Please Enter Valid Mobile Number");

        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {

            CToastMessage.getInstance().showToast(getActivity(), "Please Enter Password");

        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {

            CToastMessage.getInstance().showToast(getActivity(), "Please enter correct Password");

        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {

            CToastMessage.getInstance().showToast(getActivity(), "You are blocked as You finished your all attempt");

        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {

            CToastMessage.getInstance().showToast(getActivity(), "Connection Lost ! Please Try Again");

        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {

            CToastMessage.getInstance().showToast(getActivity(), "User not found ! Kindly Regiter before Login");

        } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) {

            CToastMessage.getInstance().showToast(getActivity(), "Otp not Verify ! Kindly Generate Otp on Sign Up");
        }
    }
}

4 个答案:

答案 0 :(得分:6)

您需要访问需要调用片段的Activity的上下文。

假设您在名为startLoginFragment(Context context)的方法中拥有相应Activity的上下文。该方法的代码如下:

public void startLoginFragmemt(Context context) {
    Activity activity = (Activity) context;
    FragmentManager fragmentManager = activity.getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    LoginFragment fragment = new LoginFragment();
    fragmentTransaction.add(R.id.fragment_container, fragment);
    fragmentTransaction.commit();
}

答案 1 :(得分:1)

您可以从活动中创建片段,但是您不应该在活动之外使用它们,因为只有在附加到活动时才会调用它们的生命周期方法。

如果要操作Fragment中的数据,可以创建Fragment类。从Activity构造并对其进行膨胀,然后使用公共方法从另一个类访问它以修改信息。

在您的情况下,您可以:

  • LoginFragment:处理UI元素的类
  • LoginActivity:膨胀LoginFragment并调用Login服务。
  • LoginService:它处理登录服务(AsyncTask?),当它完成后,它会向LoginActivity返回您需要的信息,并且Activity会将更新发送到Fragment,最终将处理信息。

一些代码..正如我在评论中所说,这段代码可能不是很有用..一切都取决于你如何处理所有事情......我个人喜欢使用AsyncTask和自定义接口,我用它来创建回调之间的回调任务和UI线程(使用它们在它们之间交换数据并触发UI更改)。这段代码并没有向您展示这种方法,而是您应该如何(以我的拙见)组织您的流程

片段:

Class LoginFragment extends Fragment {

    private PROP1 prop1;
    private PROP2 prop2;

    private LoginFragment(){}

    public static LoginFragment createInstance( PROP1 prop1, PROP2 prop2){
        this.prop1 = prop1;
        this.prop2 = prop2;
    }

    // Fragment lifecycle methods

    // Methods used by activity to trigger changes in UI..
    // They could be setters or.. really.. whatever fits best in your flow. 
    public void changeProp1(PROP1 prop1){
         this.prop1 = prop1;
         // EDIT UI ELEMENTS.. DO WHATEVER YOU NEED TO DO..
    }
}

活动:

Class LoginActivity extends Activity { // Activity or whatever Activity class you're using.

     private LoginFragment mLoginFragment;

     @Override
     public void onCreate(){ // I don't remember the correct signature

          // Create LoginFragment
          mLoginFragmet = LoginFragment.newInstance(prop1,prop2)
          // Use FragmentManager to inflate your fragment
     }

     public void serviceInvoke(){ // I don't remember the correct signature

          // Invoke your login service. I'd use an AsyncTask and an interface implementation that allows the usage of callbacks
          // When the service is complete take the result value and pass it to the proper Fragment method
          mLoginFragment.changeProp1(theResultOfTheService);
     }
}

答案 2 :(得分:1)

如果您使用AppCompatActivity,则相应地投射context,否则您将获得Illegel施放异常。所以使用

AppCompatActivity activity = (AppCompatActivity) context;

而非简单activity

Activity activity = (Activity) context;

答案 3 :(得分:0)

这对我有用。

 public class YOUR_CLASS extends AppCompatActivity{

    public void changeFragments(Context context, Fragment fragment, String putStringName, String putStringDescription) {

         AppCompatActivity activity = (AppCompatActivity) context;
         // Pasar datos de un fragment a otro
         Bundle datosAEnviar = new Bundle();
         datosAEnviar.putString(putStringName, putStringDescription);
         fragment.setArguments(datosAEnviar);


        activity.getSupportFragmentManager().beginTransaction().addToBackStack(null).
            replace(R.id.nav_host_fragment, fragment).commit();
    }


}