java - 为什么之前调用 fragment ?

标签 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 被调用,如果我在第二个 fragment 中放置一个我想看到的 Toast,我会在第一个 fragment 中查看它,因为第二个 fragment 是之前构建的。我只想在 fragment 在我的 TabbedActivity 中可视化时调用 fragment 的创建。我该怎么做?

最佳答案

TabbedActivity 在核心中使用 ViewPager 来提供滑动行为。据我了解,您希望 Fragments 只有在可见时才被实例化。但是,默认情况下,ViewPager 总是加载带有 1 个预取项目的 fragment (或项目)。您可以更改该数量,但 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>

您还应该为此 Activity 设置 NoActionBar 主题

Activity 代码:

    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 )

关于java - 为什么之前调用 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41407129/

相关文章:

Android 应用程序使用 google 帐户登录

java - Android:Viewpager OnPageChangeListener onpageselected 干扰幻灯片动画

java - Aspectj(使用 spring)- 在没有传播方法的情况下仅在抛出方法上记录一次异常抛出

java - 处理大量事件监听器?

java - 尝试在 ListView 中显示从 CSV 文件读取的数据

android - 如何在Android上实现流畅的 fragment 交易动画

android - 修复键盘打开时父 Activity 中的按钮位置

java - 使用 RSA 算法包装和解开包装时出现 InvalidKeyException

java - etat HTTP 404 -/mvc/traitementTwo.jsp - spring mvc

Android:从 Intent 接收 UsbDevice