Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

android - Switching between Fragment view

The standard way to declare fragments in a xml layout file is

<LinearLayout ...> 
    <fragment class="com.example.SomeFragment"
</LinearLayout>

where SomeFragment is a java class defined like

class SomeFragment extends Fragment { 
    ... 
}

Lets say, I have 3 fragments; fragment1, fragment2, and fragment3. When the user launches the app, I show them fragment1, and when they click on a button, I replace the fragment1 with fragment2, etc.

What is the best approach to define the 3 fragments in a single layout xml file?

question from:https://stackoverflow.com/questions/7793576/switching-between-fragment-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should use a FrameLayout for that, that way you don't have to specify the fragment class in the XML and that way it is not limited to one class.

<FrameLayout 
    android:id="@+id/contentFragment"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_weight="1" />

and than you can set the fragment in the code like this

Fragment fragment = new YourFragment();

FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
transaction.replace(R.id.contentFragment, fragment);
transaction.commit();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...