Как установить несколько фрагментов, имеющих одинаковую структуру в viewpager? - PullRequest
0 голосов
/ 15 апреля 2020

Я новичок, который изучает курс Android basi c. Я хочу сделать 6 фрагментов, имеющих одинаковую структуру (только заголовок, изображение, тексты будут разными), используя один фрагмент. Я попробовал этот код, но вижу только один фрагмент.

MainActivity. java

public class MainActivity extends AppCompatActivity {

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

    viewPager = (ViewPager) findViewById(R.id.fragment_container);

    MoviePagerAdapter adapter = new MoviePagerAdapter(getSupportFragmentManager());

    mainfragment = new MainFragment();
    adapter.addItem(mainfragment);


    viewPager.setAdapter(adapter);
    viewPager.setOffscreenPageLimit(6);
}

Адаптер ViewPager (в MainActivity)

class MoviePagerAdapter extends FragmentStatePagerAdapter {

    public ArrayList<Fragment> items = new ArrayList<Fragment>();


    @Override
    public Fragment getItem(int position) {
        return items.get(position);
    }
    public MoviePagerAdapter(@NonNull FragmentManager fm) {
        super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
    }
    public void addItem(Fragment item) {
        items.add(item);
    }
    @Override
    public int getCount() {
        return items.size();
    }
}

MainFragment. java

public class MainFragment extends androidx.fragment.app.Fragment {

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.main_frargment, container,
            false);

   //...

    'i want to make 6fragments with datas below '
    movieData = new MovieData("title1", "rate1", "grade1");
    addData(movieData);
    movieData = new MovieData("title2", "rate2", "grade2");
    addData(movieData);
    movieData = new MovieData("title3", "rate3", "grade3");
    addData(movieData);
    movieData = new MovieData("title4", "rate4", "grade4");
    addData(movieData);
    movieData = new MovieData("title5", "rate5", "grade5");
    addData(movieData);
    movieData = new MovieData("title6", "rate6", "grade6");
    addData(movieData);

    return rootView;
}
public void addData(MovieData movieData){
    Bundle bundle = new Bundle();
    bundle.putParcelable("data", movieData);
    MainFragment mainFragment = new MainFragment();
    mainFragment.setArguments(bundle);
    title.setText(movieData.title);
    reservation_rate.setText(movieData.getReservation_rate());
    grade.setText(movieData.getGrade());
    image.setImageResource(R.drawable.image6);
}

}

1 Ответ

0 голосов
/ 15 апреля 2020

измените свой код следующим образом:

 public class MainActivity extends AppCompatActivity {

 private MoviePagerAdapter adapter;

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

 viewPager = (ViewPager) findViewById(R.id.fragment_container);

 adapter = new MoviePagerAdapter(getSupportFragmentManager());
 viewPager.setAdapter(adapter);
 viewPager.setOffscreenPageLimit(6);


 for(int i =0;i<6;i++){
        createFrag(i);
    }
 }
}

private void createFrag(int number) {
    MainFragment fragment = new MainFragment();
    Bundle args = new Bundle();
    args.putInt("NUMBER",number);
    fragment.setArguments(args);
    adapter.addItem(fragment);
    adapter.notifyDataSetChanged();
}


class MoviePagerAdapter extends FragmentStatePagerAdapter {

 public ArrayList<Fragment> items = new ArrayList<Fragment>();


 @Override
 public Fragment getItem(int position) {
   return items.get(position);
 }
 public MoviePagerAdapter(@NonNull FragmentManager fm) {
   super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
 }
 public void addItem(Fragment item) {
   items.add(item);
}
 @Override
public int getCount() {
  return items.size();
}

}

и измените свой фрагмент следующим образом:

     public class MainFragment extends androidx.fragment.app.Fragment {
     //1st
    private int number;



    @Nullable


   //this is variant 1 - with static Movie data

  @Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable 
  ViewGroup container, @Nullable Bundle savedInstanceState) {

  ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.main_frargment, 
  container,
    false);

   //...

  //2d
   assert getArguments() != null;
  number = getArguments().getInt("NUMBER");



  switch (number) {
        case 0:
            MmovieData movieData1 = new MovieData("title1", "rate1", 
     "grade1");
            addData(movieData1);
            break;
        case 1:
            MmovieData movieData2 = new MovieData("title2", "rate2", 
      "grade2");
            addData(movieData2);
            break;
        //...

    }

    return rootView;
}



  public void addData(MovieData movieData){


   title.setText(movieData.title);
   reservation_rate.setText(movieData.getReservation_rate());
   grade.setText(movieData.getGrade());
   image.setImageResource(R.drawable.image6);

  }

  }

, и это вариант 2 (с Dynami c данные и слушатель)

     public class MainFragment extends androidx.fragment.app.Fragment {
     //1st
    private int number;



    @Nullable




  @Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable 
  ViewGroup container, @Nullable Bundle savedInstanceState) {

  ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.main_frargment, 
  container,
    false);

   //...

  //2d
   assert getArguments() != null;
  number = getArguments().getInt("NUMBER");

    return rootView;
}


  //some method of listener changed
  public void dataChanged(MovieData movieData, int position){

  if(number==position){

   title.setText(movieData.title);
   reservation_rate.setText(movieData.getReservation_rate());
   grade.setText(movieData.getGrade());
   image.setImageResource(R.drawable.image6);

  }

  }
...