2016-03-22 2 views
0

Я вкладки деятельности с 1 фрагментом, этот фрагмент имеет кнопку, я хочу, когда я нажимаю кнопку это создать новый фрагмент и я могу ударить между двумя фрагментамидобавить фрагмент к пейджеру адаптеру на кнопке мыши

это основной вид деятельности

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

      } 
} 

Это фрагмент, который у меня есть.

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



} 

второй фрагмент должен пройти на создание вида сцены после нажатия кнопки, и, пожалуйста, где я ставлю каждый код, если есть способ сделать это.

ответ

1

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

Когда кнопка в фрагменте нажата следующие вещи происходят в следующей последовательности:

  1. addFragment() метод родительской активности вызываются путем передачи экземпляра фрагмента будет добавлено. Этот открытый метод используется для доступа к закрытому члену mSectionsPagerAdapter родительской активности. Мы можем покончить с этим методом, если mSectionsPagerAdapter становится общедоступным или конфиденциальным.
  2. SectionsPagerAdapter добавляет переданный фрагмент в свой список фрагментов, а затем уведомляет пейджер представления о том, что его набор данных изменился.
  3. TabLayout обновлен, чтобы разместить новый фрагмент (страница).
  4. Наконец, пейджер представления выполнен с возможностью прокрутки до добавленного фрагмента с использованием метода setCurrentItem().

Ссылка:

1

В вашем 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); 
} 

В MainActivity перед установкой адаптера с mViewPager.setAdapter(mSectionsPagerAdapter); добавить первый фрагмент (PlaceHolder в вашем случае). (или сделать это в конструкторе SectionPagerAdapter).

А затем в вашем OnClickListener позвоните по телефону SectionPagerAdapteraddFragment.

РЕДАКТИРОВАТЬ: В MainActivity:

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

жаль, что я новичок в Java, мой секции пейджера адаптер находится в основной деятельности 'частного SectionsPagerAdapter mSectionsPagerAdapter; 'Как я могу добавить код? –

+0

Добавлен код MainActivity – Automatik