Android: how to add another fragment to the main activity

烈酒焚心 提交于 2019-12-24 12:23:05

问题


I asked a question about how to add a Fragment that contained something drawn using OpenGL ES here. Someone was kind enough to answer that for me, but unfortunately today I encountered another problem. As I mentioned in my other question, my purpose is to add other Fragments next to the one that contains OpenGL and because I am a beginner in Android development I don't seem to understand how this is done.

Here's what I want: right now, my code is exactly the one from my other question. I also have this Fragment:

public class TextFragment extends Fragment 
{

    private TextView textview;

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

        View view = inflater.inflate(R.layout.text_fragment,
            container, false);

        textview = (TextView) view.findViewById(R.id.textView1);

        return view;
    }
}

together with its layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/frag2">

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="Fragment Two"
    android:textAppearance="?android:attr/textAppearanceLarge" />
 </RelativeLayout>

and I want to add this to my main activity, where right now I only have the OpenGL Fragment. Here's my main activity:

public class FragmentExampleActivity extends FragmentActivity implements ToolbarFragment.ToolbarListener 
{
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener()
        {
            public void onBackStackChanged()
            {
                int backCount = getSupportFragmentManager().getBackStackEntryCount();
                if (backCount == 0)
                {
                    finish();
                }
            }
        });

        if (savedInstanceState == null)
        {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.main_container, new OpenGLES20ActivityFrag())
                    .addToBackStack(null)
                    .commit();

        }
    }
}

and the Fragment that has OpenGL in it and that I have already added to the main activity:

public class OpenGLES20ActivityFrag extends Fragment
{
private GLSurfaceView mGLView;

public OpenGLES20ActivityFrag()
{
    super();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    mGLView = new MyGLSurfaceView(this.getActivity()); 
    return mGLView;
}


}

What I tried and failed: using another call to the .add method inside getSupportFragmentManager() or adapting this bit of code for my second Fragment

getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.frag2, TextFragment)
                .addToBackStack(null)
                .commit();

that gave me an 'expression expected' error in the add method. I tried adding this constructor to my second Fragment

public TextFragment()
{
    super();
}    

and then inside the add method I put .add(R.id.frag2, new TextFragment())

which still didn't work.


回答1:


In order to dynamically add a Fragment to a layout, what you need is a container (like in your case, it was R.id.main_container). Thus, if you want to add multiple fragments, what you need is multiple containers, like so:

<LinearLayout android:orientation="vertical" android:layout_height="fill_parent" android:layout_width="fill_parent">
  <FrameLayout android:id="@+id/main_container_1" android:layout_weight="1" android:layout_height="fill_parent" android:layout_width="fill_parent"/>
  <FrameLayout android:id="@+id/main_container_2" android:layout_weight="1" android:layout_height="fill_parent" android:layout_width="fill_parent"/>
</LinearLayout>

(this snippet is from How to split the screen with two equal LinearLayouts? )

And then you would need to add the two Fragments:

if (savedInstanceState == null)
{
    getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.main_container_1, new OpenGLES20ActivityFrag())
            .commit();

    getSupportFragmentManager()
            .beginTransaction()
            .add(R.id.main_container_2, new TextFragment())
            .commit();
}

Please note that with multiple Fragments on a single Activity, it's better not to add them to the backstack, because then you'd have to press Back as many times as there are Fragments, and in this case it's more reasonable to navigate between the "views" or states of the application with Activities, and not by replacing the Fragments.

(considering the backstack doesn't change, I don't think the backstack listener needs to be removed, but that's done so that if you press Back, you don't end the Activity, but the Fragments within it first if you have them added to the backstack. But the Activity doesn't end when it contains no fragments, and you'd have an "empty view", hence why that was added.)

Please also check if the rotation works and data is maintained even after the activity reconstruction, because there's a chance you need to set the retain instance state to true explicitly on the Fragments for that to work.



来源:https://stackoverflow.com/questions/24905272/android-how-to-add-another-fragment-to-the-main-activity

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