之前为什么要调用片段?

时间:2016-12-31 09:35:25

标签: java android android-fragments fragment

考虑TabbedActivity的这部分代码:

public class MainActivity extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    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();
        }
    });

}


@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);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
        switch (getArguments().getInt(ARG_SECTION_NUMBER))
        {
            case 1:
                View rootView = inflater.inflate(R.layout.fragment_main, container, false);
                return rootView;

            case 2:
                View rootView2 = inflater.inflate(R.layout.fragment_main, container, false);
                Toast.makeText(getContext(),"FRAGMENT 2 BUILT WHEN WE VIEW FRAGMENT 1! ",Toast.LENGTH_LONG).show();
                return rootView2;

            case 3:
                View rootView3 = inflater.inflate(R.layout.fragment_main, container, false);
                return rootView3;

            default:
                View rootView0 = inflater.inflate(R.layout.fragment_main, container, false);
                return rootView0;
        }
    }
}

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 3;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
        }
        return null;
    }
}

}

当我们在案例1中时,案例2被调用,如果我在第二个片段中放置了我想要看的Toast,我在第一个看起来因为第二个是之前构建的。我想只在片段在我的TabbedActivity中可视化时才调用片段的创建。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

TabbedActivity在核心中使用ViewPager来提供滑动行为。据我了解,您希望片段只有在可见时才会被实例化。但是,默认情况下,ViewPager始终使用1个预取项加载片段(或项)。您可以更改该金额,但最低为1。以下是ViewPager类的代码:

public void setOffscreenPageLimit(int limit) {
    if (limit < DEFAULT_OFFSCREEN_PAGES) {
        Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to "
                + DEFAULT_OFFSCREEN_PAGES);
        limit = DEFAULT_OFFSCREEN_PAGES;
    }
    if (limit != mOffscreenPageLimit) {
        mOffscreenPageLimit = limit;
        populate();
    }
}

因此,使用ViewPager,您无法实现目标。您可以使用TabLayout实现类似的行为

使用TabLayout的XML布局:

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

    <android.support.v7.widget.Toolbar
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:background="@color/colorPrimary"
        app:contentInsetStart="0dp">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:tabIndicatorColor="#000000"
            app:tabIndicatorHeight="3dp">

            <android.support.design.widget.TabItem
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Tab 1" />

            <android.support.design.widget.TabItem
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Tab 2" />

            <android.support.design.widget.TabItem
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Tab 3" />

            <android.support.design.widget.TabItem
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Tab 4" />

        </android.support.design.widget.TabLayout>
    </android.support.v7.widget.Toolbar>

    <FrameLayout
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>

您还应该为此活动设置NoActionBar主题

活动代码:

    public class TabbedActivity extends AppCompatActivity {

    private SparseArrayCompat<Fragment> fragments = new SparseArrayCompat<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabbed_activity);
        setTitle("");
        fragments.put(0, new Fragment()); //Here you need to instantiate your fragments
        fragments.put(1, new Fragment()); // instead of new Fragment()
        fragments.put(2, new Fragment()); // like new Tab1Fragment()
        fragments.put(3, new Fragment());
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                changeFragment(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        changeFragment(0);
    }

    private void changeFragment(int position) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        Fragment fragment = fragments.get(position);
        String transactionTag = fragment.getClass().getSimpleName();
        if (fragmentManager.getBackStackEntryCount() > 0 &&
                fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount() - 1).getName()
                        .equalsIgnoreCase(transactionTag)) {
            return;
        }
        transaction.replace(R.id.fragmentContainer, fragment, transactionTag);
        transaction.commitAllowingStateLoss();
    }
}

TabLayout非常灵活,请在此处详细了解(https://guides.codepath.com/android/google-play-style-tabs-using-tablayout