从片段中调用片段

时间:2016-02-29 12:04:55

标签: android android-fragments fragment

我想通过点击当前片段中的按钮来调用当前片段中的另一个片段。

这是我的主要活动:

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;
    }
}

这是我的一个片段:

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

假设我想在点击上从上面的片段调用resultsfragment 一个id为btn_search的按钮,那我该怎么办? 我在这里尝试了一些现有的答案,没有运气! P.S:我是android dev世界的先驱。

5 个答案:

答案 0 :(得分:3)

进行片段交易。请执行以下操作。

例如..  A和B是片段。  目前A对用户可见。如果你想做一个交易。 只需创建如下所示

 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();
    }

答案 1 :(得分:0)

使用接口在片段之间进行通信。例如

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();
    }
}

然后在你的活动中

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

}

答案 2 :(得分:-1)

您应该在活动中创建一些方法。据说它看起来像这样:

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

正如您在onNavigationItemSelected

中所做的那样

然后,从您的片段中,您可以调用

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

例如

答案 3 :(得分:-1)

首先,您需要创建一个接口,该接口定义您的片段将使用的方法来调用附加到其相应活动的代码

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

创建界面后,执行任何使用此片段的活动。

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.
    }
}

然后在你的片段的onAttach中进行一个活动,一定要检查附加活动是否实现了这个接口,否则就像这样抛出一个RunTimeException

@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");
    }
}

此处mListener是您在片段类中保存的接口引用,通过该接口引用,在实际发生单击时调用onClickOfMyView()方法

您的片段类,其中包含视图的点击代码。

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

答案 4 :(得分:-1)

在MainActivity中创建方法switchFragment

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();
            }

        }

现在来自您当前的片段,您可以通过以下代码调用此MainActivity的功能

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

如果这适合您,请告诉我! :)