在选项卡式活动中添加和替换片段

时间:2016-03-08 08:30:09

标签: android android-fragments android-tabbed-activity

我在Android Studio中创建了一个示例选项卡式活动,现在我想在其中显示一些我自己的片段,而不是默认的占位符文本。

在其他项目中,我会创建一个空白片段,只需使用以下代码添加:

BlankFragment1 blankFragment1 = new BlankFragment1();
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, blankFragment1).commit();

如果我导入空白片段类和xml布局并简单地将这两行粘贴到PlaceholderFragment类中,我得到

Non-Static method cannot be referenced from a static context

所以,我尝试创建一个PlaceholderFragment实例并在其上调用getSupportFragmentManager()

PlaceholderFragment placeholderFragment = new PlaceholderFragment();
        placeholderFragment.getSupportFragmentManager().beginTransaction().add(R.id.container, blankFragment1).commit();

但现在我得到了

Cannot resolve method 'getSupportFragmentManager()'

所以我认为可能有更好更简单的方法来做这件事。

在选项卡式活动中使用某些现有片段的最佳方法是什么?

作为参考,这是整个MainActivity类:

public class MainActivity extends FragmentActivity implements BlankFragment1.OnFragmentInteractionListener {

/**
 * 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);

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

@Override
public void onFragmentInteraction(Uri uri) {
    //
}

/**
 * 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) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        BlankFragment1 blankFragment1 = new BlankFragment1();
        PlaceholderFragment placeholderFragment = new PlaceholderFragment();
        placeholderFragment.getSupportFragmentManager().beginTransaction().add(R.id.container, blankFragment1).commit();
        //textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}

/**
 * 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;
    }
 }
}                         

2 个答案:

答案 0 :(得分:5)

从适配器的getItem(int position)方法提供Fragment。

默认情况下,使用的适配器是SectionsPagerAdapter。转到SectionsPagerAdapter,里面有一个名为

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

在这里,您应该返回您想要片段的位置片段。例如,如果我希望我的片段出现在标签号0中,那么它应该如下所示。

@Override
    public Fragment getItem(int position) {
        if(position == 0){
           return new YourExistingFragment();
        }
        else
        return PlaceholderFragment.newInstance(position + 1);
    }

答案 1 :(得分:0)

您可能正在从静态方法调用getSupportFragmentManager()。需要查看更多代码。

第二种情况不起作用,因为getSupportFragmentManager()FragmentActivity的方法,而不是PlaceholderFragment。