选择选项卡或滑动页面时如何加载片段

Posted

技术标签:

【中文标题】选择选项卡或滑动页面时如何加载片段【英文标题】:How to load the fragments when the tab is selected or page is swiped 【发布时间】:2016-06-06 07:08:49 【问题描述】:

当我滑动标签时,标签正在改变,但我附加的片段没有加载。 我创建了 4 个片段及其布局 我在 mainActivity 类中包含了 pagerAdapter output(showing blank page when tab is selected) 这是我的 MainActivity.java

public class MainActivity extends AppCompatActivity 
private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setOnTabSelectedListener(onTabSelectedListener(viewPager));



private void setupViewPager(ViewPager viewPager) 
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new FragmentOne(), "Home");
    adapter.addFragment(new FragmentTwo(), "e-Profile");
    adapter.addFragment(new FragmentThree(), "Results");
    adapter.addFragment(new FragmentFour(), "Outpass");
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    onTabSelectedListener(viewPager);


private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager pager) 
    return new TabLayout.OnTabSelectedListener() 
        @Override
        public void onTabSelected(TabLayout.Tab tab) 
            pager.setCurrentItem(tab.getPosition());
        

        @Override
        public void onTabUnselected(TabLayout.Tab tab) 

        

        @Override
        public void onTabReselected(TabLayout.Tab tab) 

        
    ;


这是我的 viewpagerAdapter。

class ViewPagerAdapter extends FragmentPagerAdapter 
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public ViewPagerAdapter(FragmentManager manager) 
    super(manager);


@Override
public Fragment getItem(int position) 
    return mFragmentList.get(position);


@Override
public int getCount() 
    return mFragmentList.size();


public void addFragment(Fragment fragment, String title) 
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);


@Override
public CharSequence getPageTitle(int position) 
    return mFragmentTitleList.get(position);


我的片段

public class FragmentOne extends Fragment

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
    return inflater.inflate(R.layout.fragment_one, container, false);



【问题讨论】:

【参考方案1】:

请按照以下代码操作。将您的代码与此进行比较。它对我来说非常有用。

我的活动:

public class MainActivity extends AppCompatActivity 


private TabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    tabLayout.setOnTabSelectedListener(onTabSelectedListener(viewPager));

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View view) 
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        
    );




private TabLayout.OnTabSelectedListener onTabSelectedListener(final ViewPager viewPager) 

    return new TabLayout.OnTabSelectedListener() 
        @Override
        public void onTabSelected(TabLayout.Tab tab) 
            viewPager.setCurrentItem(tab.getPosition());
        

        @Override
        public void onTabUnselected(TabLayout.Tab tab) 

        

        @Override
        public void onTabReselected(TabLayout.Tab tab) 

        
    ;


private void setupViewPager(ViewPager viewPager) 
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new OneFragment(), "ONE");
    adapter.addFragment(new TwoFragment(), "TWO");
    adapter.addFragment(new ThreeFragment(), "THREE");
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    onTabSelectedListener(viewPager);


@Override
public boolean onCreateOptionsMenu(Menu menu) 
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;


@Override
public boolean onOptionsItemSelected(MenuItem item) 
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in androidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) 
        return true;
    

    return super.onOptionsItemSelected(item);


class ViewPagerAdapter extends FragmentPagerAdapter 
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) 
        super(manager);
    

    @Override
    public Fragment getItem(int position) 
        return mFragmentList.get(position);
    

    @Override
    public int getCount() 
        return mFragmentList.size();
    

    public void addFragment(Fragment fragment, String title) 
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    

    @Override
    public CharSequence getPageTitle(int position) 
        return mFragmentTitleList.get(position);
    


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_
    android:layout_ android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <android.support.design.widget.AppBarLayout android:layout_
        android:layout_ android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar android:id="@+id/toolbar"
            android:layout_ android:layout_
            android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_
            android:layout_
            app:tabMode="fixed"
            app:tabGravity="fill"/>

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton android:id="@+id/fab"
        android:layout_ android:layout_
        android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_
    android:layout_ android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main" tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_
        android:layout_
        app:layout_behavior="@string/appbar_scrolling_view_behavior"  />


</RelativeLayout>

OneFragment.java

public class OneFragment extends Fragment 
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
  //  View view = inflater.inflate(R.layout.frag_one,container,false);
    return inflater.inflate(R.layout.frag_one,container,false);


frag_one.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_
    android:layout_>

    <TextView
        android:layout_
        android:layout_
        android:textSize="20sp"
        android:text="First Fragment"/>

</LinearLayout>

【讨论】:

非常感谢 Naveen Shriyan.. 现在工作正常。 我正在使用你的代码,但每次第二个标签不加载时,我想每次点击第二个标签时加载第二个标签【参考方案2】:

与您的代码 ontabselected 相同,您在此处设置当前的 viewpager 项目也在 pageselected 您必须替换您的片段

eventPager.setOnPageChangeListener(new OnPageChangeListener() 

        @Override
        public void onPageSelected(int arg0) 

            if (arg0 == 0) 
                // replace fragmen1

            
            if (arg0 == 1) 
                // replace fragment 2

            
            if (arg0 == 2) 
                // replace fragment 3



        

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) 
            // TODO Auto-generated method stub

        

        @Override
        public void onPageScrollStateChanged(int arg0) 
            // TODO Auto-generated method stub

        
    );

【讨论】:

【参考方案3】:

删除这行代码,它应该可以工作。

viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
onTabSelectedListener(viewPager);

【讨论】:

仍然面临同样的问题 嘿,这就是你不使用片段的原因,我可以在这里重现它:),只需在片段中返回视图 wooollllaaaa 它将起作用:) 如果解决了请投票:) 我正在返回视图 return inflater.inflate(R.layout.fragment_one, container, false); 你能发布那个片段吗? 是的,我已经在问题中发布了【参考方案4】:

在片段中正确返回视图:) Woolla 它应该可以工作:)

public class ThreeFragment extends Fragment 
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    View view = inflater.inflate(R.layout.frag_three,container,false);
    return view;


【讨论】:

以上是关于选择选项卡或滑动页面时如何加载片段的主要内容,如果未能解决你的问题,请参考以下文章

如何根据登录成功在新窗口/选项卡或同一窗口/选项卡中打开页面?

如何在关闭浏览器选项卡或浏览器时插入数据[重复]

如果音频正在另一个选项卡或窗口中播放,如何关闭声音

单击时如何在新选项卡或(新窗口)中重定向超链接?

单击ListViewItem时Android加载片段

如何在片段选项卡中添加另一个活动(例如视频活动)?