Trying to start a Fragment from an Activity.

梦想与她 提交于 2019-12-25 12:15:10

问题


I have a tabbed view which I have implemented using Action Bar tabs, now there are one or two pages which navigate away from this tab view. At some point of time I want to call one of the fragments in the foreground again. But I am not finding any example of how to do this.

Class Definition(Fragment1_2):

public class Fragment1_2 extends Fragment {

Class Definition(AdhocEdit.class):

public class AdhocEdit extends Activity{

Activity to Fragment Intent so far:

Fragment1_2 fragmentB = (Fragment1_2)getFragmentManager().findFragmentById(R.id.fragemnt1_2);

        /*  Intent mainIntent;
            mainIntent = new Intent(AdhocEdit.this,Fragment1_2.class); 
            AdhocEdit.this.startActivity(mainIntent);
            AdhocEdit.this.finish();    */


        //    startActivity(new Intent(AdhocEdit.this, Fragment1_2.class));

Commented because none of them works. Also do I need to add this Fragment1_2 into the Manifest, if so how?


回答1:


You can't start a fragment like you do for activity.

Fragment is hosted by a activity. You need to add the fragment to the container.

Example from docs

ExampleFragment fragment = new ExampleFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

fragment_container is the id of the container which is usually a FrameLayout and you add the desired fragment the container

More info @

http://developer.android.com/guide/components/fragments.html



来源:https://stackoverflow.com/questions/22016194/trying-to-start-a-fragment-from-an-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!