calling a fragment from fragment

2019-07-11 00:06发布

问题:

I want to call another fragment from the current fragment on the click of the button in the current fragment.

Here is my Mainactivity :

import android.app.FragmentManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.asd.fragments.RecommendationsFragment;
import com.asd.ibitz4college.fragments.SearchCoachingFragment;
import com.asd.fragments.SearchCollegesFragment;
import com.asd.fragments.MainFragment;
import com.asd.fragments.SearchConsultanciesFragment;
import com.asd.fragments.TrendingFragment;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();





    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame,new MainFragment()).commit();

        if (id == R.id.search_colleges) {
            // Handle the Search Colleges action
            fm.beginTransaction().replace(R.id.content_frame,new SearchCollegesFragment()).commit();

        }

         else if (id == R.id.search_consultancies) {
            fm.beginTransaction().replace(R.id.content_frame,new SearchConsultanciesFragment()).commit();

        }


        else if (id == R.id.search_coaching) {

            fm.beginTransaction().replace(R.id.content_frame,new SearchCoachingFragment()).commit();


        }

        else if (id == R.id.my_recommendations) {
         fm.beginTransaction().replace(R.id.content_frame, new RecommendationsFragment()).commit();

        }

         else if (id == R.id.trending) {

            fm.beginTransaction().replace(R.id.content_frame, new TrendingFragment()).commit();


        } else if (id == R.id.profile) {

        } else if (id == R.id.logout) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Here is one of my fragment :

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.asd.k4c.R;


public class SearchCoachingFragment extends Fragment  {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

            View rootview = inflater.inflate(R.layout.fragment_search_coaching,container,false);
            return rootview;



    }
} //Update code formatting

Suppose I want to call resultsfragment from the above fragment on the click of a button whose id is btn_search, then what should I do? I tried some already existing answers here, no luck! P.S: I'm a starter to the world of android dev.

回答1:

For doing a fragment transaction.Please do the following.

Eg.. A and B are fragments. Currently A is visible to the User. If you want to do a transaction. Just create as like below

 B b = new B(); 
((YourActivity)getActivity).setnewFragment(b,true);

public void setNewFragment(Fragment fragment,boolean addbackstack) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fragment_content, fragment);
        if (addbackstack)
            transaction.addToBackStack(title);
        transaction.commit();
    }


回答2:

Use an interface to communicate between fragments. For example

public YourFirstFragment extends Fragment {

    public interface FragmentCallBack {
        void callBack();
    }

    private FragmentCallBack fragmentCallBack;

    public void setFragmentCallBack(FragmentCallBack fragmentCallBack) {
        this.fragmentCallBack = fragmentCallBack;
    }

    private void callThisWhenYouWantToCallTheOtherFragment(){
        fragmentCallBack.callBack();
    }
}

Then in You activity

private void setCallToFragment{
  yourFirstFragment.setFragmentCallBack(new FragmentCallBack(){
   void callBack(){
    yourSecondFragment.doWhatEver();
  }})

}


回答3:

You should create some method in your activity. Supposedly it will look like this :

public void startFragment(Fragment fragment) {
    fm.beginTransaction().replace(R.id.content_frame,new fragment).commit();
}

As you already done in youronNavigationItemSelected

Then, from your fragment, you can call

((MainActivity)getActivity()).startFragment(new SearchConsultanciesFragment()) 

for example



回答4:

Create a method switchFragment in your MainActivity

FragmentTransaction ft;

    public void switchFrag() {
            try {
                    ft = getActivity().getFragmentManager().beginTransaction();
                    ft.replace(R.id.frame_container, new Your_Fragment.class);
                    ft.commit();
                } else {
                    Log.e("test", "else part fragment ");
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

Now from your current Fragment you can call this MainActivity's funciton throught the below code:

((MainActivity)getActivity()).switchFrag();

Let me know if this works for you! :)



回答5:

First you need to create an interface which defines methods that will be used by your fragment to invoke code from the respective activity it is attached to

public interface OnFragmentInteractionlistener {
    // the method that you call from your fragment, 
    // add whatever parameter you need in the implementation of this
    // method.
    void onClickOfMyView();
}

once you have created the interface, implement it any and all activities that use this fragment.

public class MainActivity extends AppCompatActivity
        implements OnMyFragmentInteractionListener {

    @Override
    public void onClickOfMyView() {
        // DO your on click logic here, like starting the transaction
        // to add/replace another fragment.
    }
}

Then in the onAttach of your fragment to an activity be sure to check if the attaching activity implements this interface, else throw a RunTimeException like so

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnMyFragmentInteractionListener) {
        mListener = (OnMyFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnMyFragmentInteractionListener");
    }
}

Here mListener is a interface reference you hold in your fragment class through which you invoke the onClickOfMyView() method when actually the click happens

Your fragment class where the view's click code is there.

myView.setOnClickListener(new View.OnClickListener(){
    @Override
    public void onClick(View v) {
        mListener.onClickOfMyview();
    }
});