简体   繁体   English

处理Android ViewPager,片段和内部内容

[英]Dealing with Android ViewPager, Fragments and stuff inside

So basically, 所以基本上

I'm using the slidingTabLayout and slidingTabStrip 我正在使用slideTabLayoutslideTabStrip

I have a ViewPager: 我有一个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>

Which gets filled with a adapter on my MainActivity.java: 哪个在我的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);
}

The TabsViewPagerAdapter returns a Fragment, depending on the tab position: TabsViewPagerAdapter返回一个Fragment,具体取决于标签的位置:

public Fragment getItem(int position) {

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

finally, each fragment contains this simple layout: 最后,每个片段都包含以下简单布局:

<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>

The tabs are rendering pretty well and working. 选项卡呈现得很好并且可以正常工作。 Now I have two questions since I'm newbie: 现在,我是新手,有两个问题:

  1. How can I access this fragment from the main activity so I can change the inner textView text for example? 如何从主要活动中访问此片段,例如可以更改内部textView文本?

  2. In case it is possible to access the fragment, is it better to replace the fragment for data changes or dynamically change the data inside? 如果可以访问该片段,是否最好替换该片段以进行数据更改或动态更改内部数据?

you can change inner TextView text from fragment, no need to accessing from your Activity but in case that you want access to Fragment , you can use getFragmentByTag function. 您可以从片段中更改内部TextView文本,无需从Activity进行访问,但是如果要访问Fragment ,则可以使用getFragmentByTag函数。

here is a helpful link describing how to achieve this goal. 是一个有用的链接,描述了如何实现此目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM