【问题标题】:Dealing with Android ViewPager, Fragments and stuff inside处理Android ViewPager, Fragments 和里面的东西
【发布时间】:2015-09-03 12:23:34
【问题描述】:

基本上,

我正在使用slidingTabLayoutslidingTabStrip

我有一个 ViewPager:

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

在我的 MainActivity.java 上填充了一个适配器:

private ViewPager pager;
private TabsViewPagerAdapter adapter;
private SlidingTabLayout tabs;

protected void onCreate(Bundle savedInstanceState) {
    adapter =  new TabsViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);

        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);

        tabs = (SlidingTabLayout) findViewById(R.id.tabs);
        tabs.setDistributeEvenly(true);
        tabs.setViewPager(pager);
}

TabsViewPagerAdapter 根据标签位置返回一个 Fragment:

public Fragment getItem(int position) {

    if(position == 0)
    {
        PersonalTab tab1 = new PersonalTab();
        return tab1;
    }
    else
    {
        GroupTab tab2 = new GroupTab();
        return tab2;
    }
}

最后,每个片段都包含这个简单的布局:

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

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:id="@+id/textView"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

这些选项卡的渲染效果非常好并且可以正常工作。 现在我有两个问题,因为我是新手:

  1. 如何从主要活动访问此片段,以便更改内部 textView 文本?

  2. 万一可以访问到fragment,是更换fragment来改变数据还是动态改变里面的数据?

【问题讨论】:

    标签: java android android-fragments android-5.0-lollipop material-design


    【解决方案1】:

    您可以从片段中更改内部TextView 文本,无需从您的Activity 访问,但如果您想访问Fragment,您可以使用getFragmentByTag 函数。

    here 是一个有用的链接,描述了如何实现这一目标。

    【讨论】:

    • 你的意思是在我的片段中调用一个函数?这很好,但我如何获取我的片段实例,以便能够调用此函数 - 将查看您的链接!
    • 没有。您可以从您的活动中致电findFragmentByTag。您必须为每个片段设置一个标签,然后找到带有该标签的片段。上面链接中的示例已对其进行了完整的解释。
    • 您好!我实际上并没有使用 getFragmentByTag,而是遵循了这个answer,它工作得很好。如果使用这种方法有任何不利之处,了解一下会很有用:)
    • 这个答案在某种程度上是相等的。在这种方法中,您应该创建自己的包含Fragments 的列表(或数组或其他内容)并手动添加/删除它们,但使用getFragmentByTag,您不必执行这些工作。但如果该链接对您有用,请使用它。
    猜你喜欢
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 2018-05-29
    • 1970-01-01
    相关资源
    最近更新 更多