如何在这十二个片段之间切换

时间:2014-07-20 17:37:37

标签: android xml android-fragments android-fragmentactivity

大家好我正在尝试为一个可以切换十二个不同片段的项目演示制作一个非常简单的应用程序。我想从一个片段开始,然后使用ontouch侦听器切换到下一个。这是我的主要xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context="com.example.demoww.MainActivity" >

    <fragment class="com.example.demoww.suggestedfriend"
    android:id="@+id/suggestedfriendLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>

    <fragment class="com.example.demoww.profile"
    android:id="@+id/ProfileLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"/>

    <fragment class="com.example.demoww.messages"
    android:id="@+id/messagesLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"/>
    <fragment class="com.exmaple.demoww.friendslist"
    android:id ="@+id/friendslistlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"/>

    <fragment class="com.example.demoww.raul_message"
    android:id="@+id/examplemessagelayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"/>

    <fragment class="com.example.demoww.raul_profile"
    android:id="@+id/raulprofileLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"/>

    <fragment class="com.example.demoww.requests"
    android:id="@+id/requestsLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"/>

    <fragment class="com.example.demoww.search"
    android:id="@+id/searchlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:visibility="gone"/>

</LinearLayout>

这是第一个活动的类:

public class suggestedfriends extends Fragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.search,
            container, false);
        view.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return true;
            }
        });
        return view;
      }




}

我正试图找到一种方法在主活动中切换片段而不改变man xml。我担心使用片段管理器可能会以某种方式改变主xml。而且我还担心设置其他内容的可见性会使片段在后台运行,使我的模拟器变慢。

任何帮助都会受到赞赏,因为我只是一个简单的商业专业,对CS / android设计并不是很了解。

1 个答案:

答案 0 :(得分:0)

将碎片添加到Xml会将它们设置为静态碎片,这意味着无法移除或替换它们 所以你有2个选项:

1.将它们添加为动态片段,以便您可以使用getFragmentManager / getSupportFragmentManager添加/替换片段 2.使用Viewpager并将片段添加到适配器,并且能够在它们之间滑动

希望它有所帮助。