【发布时间】:2015-02-13 06:32:37
【问题描述】:
我有一个 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(即片段。)并在其中设置文本和图像并在 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>
【问题讨论】:
-
@user3471174 您是否考虑将其保存在数据库或共享首选项中?
标签: android android-fragments android-viewpager