简体   繁体   English

单击按钮将片段添加到寻呼机适配器

[英]add fragment to pager adapter on button click

I have a tabbed activity with 1 fragment, this fragment has a button, i want when i click the button it create a new fragment and i can swipe between the two fragments 我有一个带1个片段的选项卡式活动,该片段有一个按钮,我想当我单击按钮时创建一个新片段,我可以在两个片段之间滑动

this is the main activity 这是主要活动

public class ActivityBeamRec extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;

    public static CustomViewPager mViewPager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_activity_beam_rec);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        // Set up the ViewPager with the sections adapter.
        mViewPager = (CustomViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setPagingEnabled(false);

            }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
                       switch (position){
                case 0 : return PlaceholderFragment.newInstance(position + 1);
         //       case 1 : return the new fragment ;
            }
            return null;
        }

        @Override
        public int getCount() {

            return 1 ; 
        }

            }
}

this is the fragment i have. 这是我的片段。

public  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) {
        final View rootView = inflater.inflate(R.layout.fragment_activity_beam_rec, container, false);

        final EditText etxb;
     etxb = (EditText)rootView.findViewById(R.id.editText);
     final Button buDesign = (Button)rootView.findViewById(R.id.buDesign);

        buDesign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
    double b;          
    b = Double.valueOf(etxb.getText().toString());

\\here i want the button to create the second fragment and pass the variable d to it
 ActivityBeamRec.mViewPager.setPagingEnabled(true); // this is to enable the siwpe between the fragments
ActivityBeamRec.mViewPager.setCurrentItem(2); // ths is to set the new fragment as the current view

            }
        });
        return rootView;
    }



}

the second fragment should go through on create view stage after the button is pressed, and please tell where i put each code if there is a way to do this. 按下按钮后,第二个片段应该进入创建视图阶段,如果可以的话,请告诉我将每个代码放在哪里。

ActivityBeamRec: ActivityBeamRec:

public class ActivityBeamRec extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;

    private TabLayout tabLayout;

    @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) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
    }


    @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 {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        // This list holds the fragments for the pages displayed by view pager.
        private List < Fragment > fragments = new ArrayList < Fragment > ();

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
            // Add the first fragment:
            fragments.add(PlaceholderFragment.newInstance(1));
        }

        private void addFragment(Fragment fragment) {
            fragments.add(fragment);

            // Notify view pager that the contents of the adapter has changed and that it needs to update
            // its pages:
            notifyDataSetChanged();

            // Since content of view pager has changed, re-wire tab layout:
            tabLayout.setupWithViewPager(mViewPager);

            // Set the current page in the view pager to the last added fragment:
            mViewPager.setCurrentItem(fragments.size() - 1);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // Set the tab title as the number of the current section:
            return "SECTION " + (position + 1);
        }
    }

    /**
     * Adds a new fragment (page) to the view pager.
     * This method can either be public or package-private (without any modifier) depending on the package
     * of 'PlaceholderFragment'. Since you're new to Java please refer the link to access modifiers below.
     *
     * @param fragment the fragment to be added to the view pager
     **/
    public void addFragment(Fragment fragment) {
        mSectionsPagerAdapter.addFragment(fragment);
    }

    /**
     * Returns the number of the next section (page) to be added.
     *
     * @return the next section number
     */
    public int getNextSectionNumber() {
        return mSectionsPagerAdapter.getCount() + 1;
    }

}

PlaceholderFragment: 占位符片段:

public 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) {
        final View rootView = inflater.inflate(R.layout.fragment_activity_beam_rec, container, false);

        final EditText etxb;
        etxb = (EditText) rootView.findViewById(R.id.editText);
        final Button buDesign = (Button) rootView.findViewById(R.id.buDesign);

        buDesign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                double b;
                b = Double.valueOf(etxb.getText().toString());

                //here i want the button to create the second fragment and pass the variable d to it
                int nextSectionNumber = ((ActivityBeamRec) getActivity()).getNextSectionNumber();
                ((ActivityBeamRec) getActivity()).addFragment(PlaceholderFragment.newInstance(nextSectionNumber));
            }
        });
        return rootView;
    }
}

When the button in the fragment is clicked the following things occur in sequence: 单击片段中的按钮时,将依次发生以下情况:

  1. addFragment() method of parent activity is called by passing the fragment instance to be added. 通过传递要添加的片段实例来调用父活动的addFragment()方法。 This public method is used to access the private member mSectionsPagerAdapter of parent activity. 此公共方法用于访问父活动的私有成员mSectionsPagerAdapter We can do away with this method if mSectionsPagerAdapter is made public or package-private. 如果将mSectionsPagerAdapter公共或程序包私有,则可以取消此方法。
  2. SectionsPagerAdapter adds the passed-in fragment to its list of fragments and then notifies the view pager that its data set has changed. SectionsPagerAdapter将传入的片段添加到其片段列表中,然后通知视图分页器其数据集已更改。
  3. TabLayout is refreshed to accommodate the new fragment (page). TabLayout刷新以适应新的片段(页面)。
  4. Finally the view pager is made to scroll to the added fragment using the setCurrentItem() method. 最后,使用setCurrentItem()方法使视图分页器滚动到添加的片段。

Reference: 参考:

In your SectionsPagerAdapter 在您的SectionsPagerAdapter中

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

@Override
public int getCount() {
   return fragments.size();
}

@Override
public Fragment getItem(int position) {
  if(position<fragments.size())
      return fragments.get(position);
  throw new NullPointerException("No Fragment with this position found.");
}
public void addFragment(Fragment newFragment){
  fragments.add(newFragment);
}

In the MainActivity before setting the adapter with mViewPager.setAdapter(mSectionsPagerAdapter); 在MainActivity中,使用mViewPager.setAdapter(mSectionsPagerAdapter);设置适配器之前mViewPager.setAdapter(mSectionsPagerAdapter); add your first fragment(the PlaceHolder in your case). 添加您的第一个片段(在您的情况下为PlaceHolder )。 (or do it in the SectionPagerAdapter 's constructor). (或在SectionPagerAdapter的构造函数中执行此操作)。

And then in your OnClickListener call the SectionPagerAdapter 's addFragment method. 然后在您的OnClickListener调用SectionPagerAdapteraddFragment方法。

EDIT: In MainActivity: 编辑:在MainActivity中:

mSectionsPagerAdapter.addFragment(PlaceholderFragment.newInstance(0));
mSectionsPagerAdapter.setAdapter(mSectionsPagerAdapter);

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

相关问题 如何通过单击按钮在视图寻呼机中用新片段替换当前片段 - How to replace current fragment with a new fragment in a view pager with a click of a button 片段寻呼机适配器出现错误 - Fragment Pager Adapter get an error 寻呼机适配器内的片段中未显示Google地图 - Google Maps not showing in fragment within pager adapter 在Fragment Pager Adapter中保留Fragments的实例状态 - Retaining the instance state of Fragments in Fragment Pager Adapter Fragment Pager Adapter 仅显示创建的最后一个片段 - Fragment Pager Adapter only displaying last fragment created 何时/如何添加 ListView Adapter,它会通过后退按钮恢复? (分段) - When/How to add ListView Adapter, that it gets restored with back button? (Fragment) 如何在按钮上添加/删除片段? - How to add/remove Fragment on Button click? 单击另一个片段中的按钮后,在片段中添加新的文本视图 - Add new textview in fragment after click on button in another fragment 调用活动方法以从适配器实现视图分页器片段 - Calling activity method to implement view pager fragment from adapter Android:如何在TabLayout中的部分寻呼机适配器内替换/删除片段 - Android: how to replace/delete a fragment inside section pager adapter in TabLayout
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM