如何使用 Android 的 MVP 结构在 Fragment 中初始化 Presenter

How to Initialize Presenter In Fragment using MVP structure of Android

你好,我试图将 Presenter 对象初始化到我的片段中,但它抛出 ClassCastException

     E/AndroidRuntime: FATAL EXCEPTION: main  Process: com.varshaawebteam.tp_comment_mvp, PID: 22672
       java.lang.ClassCastException: com.varshaawebteam.tp_comment_mvp.HomeActivity.HomeActivity cannot be cast to com.varshaawebteam.tp_comment_mvp.TournamentListActvity.Presenter.ITournamentPresenter
        at com.varshaawebteam.tp_comment_mvp.TournamentListActvity.TournamentListFragment.onCreateView(TournamentListFragment.java:51)
                                                               at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
                                                               at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
                                                               at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                               at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                               at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                               at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                               at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                               at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                               at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                                                               at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:710)
                                                               at android.os.Handler.handleCallback(Handler.java:739)
                                                               at android.os.Handler.dispatchMessage(Handler.java:95)
                                                              at android.os.Looper.loop(Looper.java:148)
                                                               at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

HomeActivity.java(主要Class)

public class HomeActivity extends AppCompatActivity implements HomeViewInterface, IHomePresenter {

    SlidingPaneLayout slide_pane;
    HomePresenter homePresenter;
    private Toolbar mToolbar;
    SharedPreferences pref_login;
    Gson gson;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        slide_pane = (SlidingPaneLayout) findViewById(R.id.slide_pane);
        homePresenter = new HomePresenter(this, this, this);
        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        if (mToolbar != null) {
            setSupportActionBar(mToolbar);
        }

        mToolbar.setTitle("My Games");
        pref_login = getSharedPreferences(Pref_Data.PREF_LOGIN, MODE_PRIVATE);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        gson = new Gson();

        mToolbar.setNavigationIcon(R.drawable.ic_drawer);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (slide_pane.isOpen()) {
                    slide_pane.closePane();
                } else {
                    slide_pane.openPane();
                }

            }
        });

        slide_pane = (SlidingPaneLayout) findViewById(R.id.slide_pane);
        drawer_fragment menu = new drawer_fragment();
        getSupportFragmentManager().beginTransaction().add(R.id.ll_drawer, menu).commit();
        homePresenter.getdrawerselection(0);
    }

    @Override
    public void getdrawerselection(int i) {
    }

    @Override
    public void openmygamefragment() {
    }

    @Override
    public void opentournamentfragment() {
    }

    @Override
    public void setdrawerselection(int i) {
        try {
            slide_pane.closePane();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (i == 0) {
            setTitle("My Game");
            homePresenter.openmygamefragment();
            Log.e("Game:-", "Game");
        } else if (i == 1) {

            setTitle("Tournament List");
            Log.e("Tournament:-", "Tournament");
            homePresenter.opentournamentfragment();

        } else if (i == 2) {
            Toast.makeText(this, "logout", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void setmygamefragment() {

    }

    @Override
    public void settournamnetfragment() {
        TournamentListFragment tournament = new TournamentListFragment();
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.fragment_container, tournament, "frag1")
                .addToBackStack("2")
                .commit();
    }
}

TournamentPresenter.java(主持人)

public class TournamentPresenter implements ITournamentPresenter {

    private final Services services;
    private final android.content.Context context;
    private final ITournamentPresenter mListener;
    private final ITournamentView tournamentview;
    private Dialog progressDialog;
    ArrayList<TournamentRes_data> tournamentResDatas = new ArrayList<TournamentRes_data>();

    public TournamentPresenter(ITournamentPresenter listener, ITournamentView tournamentView, Context context) {
        this.mListener = listener;
        this.context = context;
        this.services = new Services();
        this.tournamentview = tournamentView;
    }

    @Override
    public void tournamentready(Response<TournamentRes> response) {

    }

    public void gettournamentlistcall(double lat, double longii) {
        progressDialog = new Dialog(context);
        progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        progressDialog.setContentView(R.layout.progress_bar_custom);
        progressDialog.setCancelable(true);
        progressDialog.show();

        services.getAPI()
                .getList_Results(lat, longii)
                .enqueue(new Callback<TournamentRes>() {
                    @Override
                    public void onResponse(Call<TournamentRes> call, Response<TournamentRes> response) {
                        if (!response.body().getDATA().isEmpty()) {
                            mListener.tournamentready(response);
                        }
                    }

                    @Override
                    public void onFailure(Call<TournamentRes> call, Throwable t) {
                        call.cancel();
                        progressDialog.dismiss();
                        Toast.makeText(context, "Server Error", Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

最后这是我的片段,我在其中遇到转换异常错误

TournamentListFragment.java(查看)

public class TournamentListFragment extends Fragment implements ITournamentPresenter, ITournamentView {
    GPSTracker gps;
    ListView lvTournaments;
    private Dialog progressDialog;
    TextView tvNoData;
    Tournament_List_Adapter tournament_list_adapter;
    TournamentPresenter tournamnetpresenter;
    ArrayList<TournamentRes_data> tournamentResDatas = new ArrayList<TournamentRes_data>();
    Context context;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.frag_tournament, container, false);
        gps = new GPSTracker(getActivity());

        context = getActivity();
        lvTournaments = (ListView) rootView.findViewById(R.id.listview);

        tvNoData = (TextView) rootView.findViewById(R.id.listview_data);
        tournamnetpresenter = new TournamentPresenter((ITournamentPresenter) getActivity(), (ITournamentView) getActivity(), getActivity());

        Toast.makeText(getActivity(), "Tournament", Toast.LENGTH_SHORT).show();

        if (gps.canGetLocation()) {
            tournamnetpresenter.gettournamentlistcall(gps.getLatitude(), gps.getLongitude());
        } else {
            gps.showSettingsAlert();
        }
        return rootView;
    }

    @Override
    public void tournamentready(Response<TournamentRes> response) {
        if (!response.body().getDATA().isEmpty()) {
            tournamentResDatas.addAll(response.body().getDATA());

            if (tournamentResDatas.size() == 0) {
                tvNoData.setVisibility(View.VISIBLE);
                tvNoData.bringToFront();
            } else {
                tvNoData.setVisibility(View.GONE);
            }

            if (tournament_list_adapter != null) {
                lvTournaments.setAdapter(tournament_list_adapter);
            } else {
                tournament_list_adapter = new Tournament_List_Adapter(getActivity(), tournamentResDatas);
                lvTournaments.setAdapter(tournament_list_adapter);
            }
        }
    }

    @Override
    public void getlistready() {

    }
}

请查看我的代码并关心帮助我。我的问题很简单,我无法在 Fragment class.

中初始化 Presenter

错误是因为您的 HomeActivity 没有实现 ITournamentPresenterTournamentListFragment 实现了。

您应该尝试将此行更改为:

tournamnetpresenter = new TournamentPresenter(this, this, getContext());