如何使用ViewPager的片段?

时间:2015-02-13 06:32:38

标签: android android-fragments android-viewpager

我有一个MainActivity和ViewPagerAdapter以及3个Tab片段,我在我的MainActivity中使用ViewPager显示它。(我也使用导航抽屉但是没问题。)

作为Android片段的初学者,我不明白如何将数据从MainActivity发送到ViewPager的Tab1,Tab2,Tab3。 我尝试使用此Send data from activity to fragment in android方法将数据从MainActivity发送到Tab1,但应用程序崩溃时出现NullPointerException。 那么我如何使用片段,以便我可以将数据从MainActivity发送到Tab1(哪个是片段。)和setText和Image,并在Viewpager中更新该片段?

MainActivity.xml

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.thewelp.materialtoolbartest1.MainActivity">

        <include
            android:id="@+id/app_bar"
            layout="@layout/app_bar">

        </include>
        <org.technoarena.tabs.SlidingTabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:layout_below="@+id/app_bar"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_below="@+id/tabs"
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:layout_weight="1"
            >

        </android.support.v4.view.ViewPager>

    </RelativeLayout>

    <fragment
        android:layout_width="@dimen/drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/fragment_drawer"
        app:layout="@layout/fragment_navigation_drawer"
        android:name="org.technoarena.technoarena2015.NavigationDrawer"
        tools:layout="@layout/fragment_navigation_drawer">

    </fragment>


</android.support.v4.widget.DrawerLayout>

Tab1.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="You Are In Tab 1"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

您可以拥有一个数据列表,并将数据传递给构造函数中的viewpager适配器,在视图分页器中,您可以将数据传递给getItem()函数中的片段。