2016-12-07 2 views
0

Je suivais exemple de l'exemple doc Android ici: https://developer.android.com/training/animation/screen-slide.htmlRemplacer Fragment dans ViewPager

Je me demandais si je veux plusieurs fragments différents sur chaque page, alors ce serait la meilleure approche.

Ceci est mon MainActivity, comme vous pouvez le voir, j'ouvre une nouvelle classe de fragments pour chaque position de la page:

public class MainActivity extends AppCompatActivity { 

    /** 
    * The number of pages (wizard steps) to show in this demo. 
    */ 
    private static final int NUM_PAGES = 4; 

    /** 
    * The pager widget, which handles animation and allows swiping horizontally to access previous 
    * and next wizard steps. 
    */ 
    private ViewPager mPager; 

    /** 
    * The pager adapter, which provides the pages to the view pager widget. 
    */ 
    private PagerAdapter mPagerAdapter; 

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

     // Instantiate a ViewPager and a PagerAdapter. 
     mPager = (ViewPager) findViewById(R.id.pager); 
     mPagerAdapter = new MainActivity.ScreenSlidePagerAdapter(getSupportFragmentManager()); 
     mPager.setAdapter(mPagerAdapter); 
    } 

    @Override 
    public void onBackPressed() { 
     if (mPager.getCurrentItem() == 0) { 
      // If the user is currently looking at the first step, allow the system to handle the 
      // Back button. This calls finish() on this activity and pops the back stack. 
      super.onBackPressed(); 
     } else { 
      // Otherwise, select the previous step. 
      mPager.setCurrentItem(mPager.getCurrentItem() - 1); 
     } 
    } 

    /** 
    * A simple pager adapter that represents 4 HeartsPageFragment objects, in 
    * sequence. 
    */ 
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter { 
     public ScreenSlidePagerAdapter(FragmentManager fm) { 
      super(fm); 
     } 

     @Override 
     public Fragment getItem(int position) { 
      switch (position) { 
       case 0: 
        return new HeartsPageFragment(); 
       case 1: 
        return new DiamondsPageFragment(); 
       case 2: 
        return new ClubsPageFragment(); 
       case 3: 
        return new SpadesPageFragment(); 
      } 
      return null; 
     } 

     @Override 
     public int getCount() { 
      return NUM_PAGES; 
     } 
    } 
} 

Ceci est l'une des classes de fragments, les quatre sont presque identiques:

public class ClubsPageFragment extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     ViewGroup rootView = (ViewGroup) inflater.inflate(
       R.layout.view_clubs, container, false); 

     return rootView; 
    } 

} 

Je me demandais s'il était préférable d'avoir quatre classes de fragments différentes pour chaque page? J'ai l'impression que c'est répétitif et mauvais, mais je ne suis pas sûr de la façon dont je pourrais régler ça. Il est en retard sur mon téléphone lorsque je passe d'un téléphone à l'autre. Tous les conseils seraient les bienvenus.

Edit:

Voici le code pour la mise en page.

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:id="@+id/content_suit" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior"> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/first_row_hearts"> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView1" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_2"/> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView2" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_3"/> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView3" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_4"/> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView4" 
      android:src="@drawable/spades_5"/> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/second_row_hearts" 
     android:layout_below="@id/first_row_hearts" 
     android:layout_marginTop="10dp"> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView5" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_6" /> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView6" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_7" /> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView7" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_8" /> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView8" 
      android:src="@drawable/spades_9" /> 


    </LinearLayout> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/third_row_hearts" 
     android:layout_below="@id/second_row_hearts" 
     android:layout_marginTop="10dp"> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView9" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_10" /> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView10" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_jack" /> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView11" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_queen" /> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView12" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_king"/> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/fourth_row_hearts" 
     android:layout_below="@+id/third_row_hearts" 
     android:layout_marginTop="10dp"> 

     <ImageView 
      android:layout_width="80dp" 
      android:layout_height="112dp" 
      android:id="@+id/imageView13" 
      android:layout_marginEnd="10dp" 
      android:src="@drawable/spades_ace"/> 
    </LinearLayout> 


</RelativeLayout> 
+0

Ce qui est en retard exactement? J'ai eu un ViewPager de 13 pages avant et aucun décalage. –

+0

J'ai 13 images sur chaque page, il y a 4 pages en tout. Et la mise en page a RelativeLayout qui a 4 LinearLayouts à l'intérieur. Chaque image a une taille de 8kB. – neX

+0

Utilisez-vous une bibliothèque de chargement d'images pour afficher ces images? Sinon, les bitmaps consomment de la mémoire rapidement. À tout moment dans le ViewPager, vous avez 39 images en mémoire. –

Répondre

2

Si vous ne voulez pas faire différentes classes de fragments, étudiez ce code généré automatiquement par android.

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; 

LeftDrawerLayout mLeftDrawerLayout; 


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

    // 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) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     TextView textView = (TextView) rootView.findViewById(R.id.section_label); 
     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 FragmentStatePagerAdapter { 

    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 7 total pages. 
     return 7; 
    } 

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

}

+0

Vous avez juste jeté le code généré automatiquement (dont la plupart était déjà dans la question). Qu'essayez-vous de montrer ici? –

+0

Lorsque vos fragments ont presque les mêmes données au lieu de créer de nouvelles classes de fragment, vous pouvez utiliser la même classe et créer de nouvelles instances (NEX a utilisé quatre fragments différents au lieu de pouvoir créer des fragments dynamiquement) –

+0

Comment est-ce différent de cette réponse? 'PlaceholderFragment.newInstance' appelle' new PlaceholderFragment', juste différentes données dans la même mise en page. Peut-être que OP veut des mises en page différentes. –