在ViewPager中加载具有不同数据的相同片段

时间:2018-03-16 10:33:14

标签: android android-fragments android-viewpager fragmentpageradapter fragmentstatepageradapter

我的viewpager中有8个具有相同布局的片段。该片段包含回收器视图和文本视图。我的问题是,当我启动viewpager片段时,所有数据都会加载到第一个片段本身上,并且其余的片段中都没有显示任何内容。以下是我在片段中设置适配器和viewpager的方法。

            adapter = new SelectPlayerAdapter(getActivity(), getChildFragmentManager());

            //Set up the view pager.
            setupViewPager(pager);

 private void setupViewPager(ViewPager viewPager) {
    adapter.addFragment(new PlayersFragment(), "BATSMAN 1", batsman_1);
    adapter.addFragment(new PlayersFragment(), "BATSMAN 2", batsman_2);
    adapter.addFragment(new PlayersFragment(), "BATSMAN 3", batsman_3);
    adapter.addFragment(new PlayersFragment(), "ALL-ROUNDER 1", all_rounder_1);
    adapter.addFragment(new PlayersFragment(), "ALL-ROUNDER 2", all_rounder_2);
    adapter.addFragment(new PlayersFragment(), "WICKET-KEEPER", wicket_keeper);
    adapter.addFragment(new PlayersFragment(), "BOWLER 1", bowler_1);
    adapter.addFragment(new PlayersFragment(), "BOWLER 2", bowler_2);
    viewPager.setAdapter(adapter);
}

这是我的Adapter类。

public class SelectPlayerAdapter extends FragmentStatePagerAdapter {

Context context = null;
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private final ArrayList<String> player_list = new ArrayList<>();
Gson gson;


public SelectPlayerAdapter(Context context, android.support.v4.app.FragmentManager mgr) {
    super(mgr);
    this.context = context;
}

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


@Override
public android.support.v4.app.Fragment getItem(int position) {
    Fragment player_fragment = mFragmentList.get(position);
    Bundle bundle = new Bundle();
    bundle.putString("player_position_string", player_list.get(position));
    player_fragment.setArguments(bundle);
    return player_fragment;
}


public void addFragment(android.support.v4.app.Fragment fragment, String title, ArrayList<Player> players_position_list) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
    gson = new Gson();
    String players_position_string = gson.toJson(players_position_list);
    player_list.add(players_position_string);
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}

我在添加片段并将它们添加到我的适配器中的不同arraylist时传递不同的arraylists,当调用get item时我从arraylist获取项目并将其作为参数传递给该片段但是当我运行它时,我最初只获取所有参数,当我更改选项卡时没有任何反应。我试过调试,看到getitem最初只调用8次,当我更改viewpager选项卡时没有任何反应。我已尝试过片段newinstance方法和addonpagechangelistener,但得到了相同的结果。请帮忙。

这是我的Players Fragment课程。

public class PlayersFragment extends Fragment {

private TextView player_position_text;
private TextView player_position_number_text;
private RecyclerView players_list_view;
Bundle extra;
private String players_string;
private ArrayList<Player> player_position_list;
Gson gson;

public PlayersFragment() {
    // Required empty public constructor
}

public static Fragment newInstance(Context context) {
    PlayersFragment playersFragment = new PlayersFragment();
    return playersFragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.select_player_layout, container, false);

    //Get the bundle from previous fragment.
    extra = this.getArguments();

    //If bundle contains the key players string then retrieve it.
    if(extra.containsKey("player_position_string")){

        players_string = extra.getString("player_position_string", "0");
        System.out.println("players string is " + players_string);
        gson = new Gson();

        Type type = new TypeToken<List<Player>>() {
        }.getType();
        player_position_list = gson.fromJson(players_string, type);
        System.out.println("players list is " + player_position_list);
        System.out.println("players name is " + player_position_list.get(1).getName());

    }

    //If bundle does not contain string it then display a toast.
    else
    {
        // Display toast with exception.
        Toast.makeText(getActivity(), "There was some error with getting the details. Please try again later.",
                Toast.LENGTH_LONG).show();
    }

    player_position_text = view.findViewById(R.id.player_position_text);
    player_position_number_text = view.findViewById(R.id.player_position_number_text);
    players_list_view = view.findViewById(R.id.players_list_view);

    return view;
}

1 个答案:

答案 0 :(得分:0)

编辑:

我添加了一个工作演示。请您检查一下,如果有效,请告诉我。

Player.java

public class Player implements Parcelable {

    private String name;
    private int age;

    public Player(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    protected Player(Parcel in) {
        name = in.readString();
        age = in.readInt();
    }

    public static final Creator<Player> CREATOR = new Creator<Player>() {
        @Override
        public Player createFromParcel(Parcel in) {
            return new Player(in);
        }

        @Override
        public Player[] newArray(int size) {
            return new Player[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
    }

    @Override
    public String toString() {
        return "Player{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

PlayerFragment.java

public class PlayerFragment extends Fragment {

    private static final String ARG_PLAYERS = "arg_player";
    private Player player;

    public static PlayerFragment newInstance(Player players) {

        Bundle args = new Bundle();
        args.putParcelable(ARG_PLAYERS, players);
        PlayerFragment fragment = new PlayerFragment();
        fragment.setArguments(args);
        return fragment;
    }

        public PlayerFragment() {
            // Required empty public constructor
        }

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle args = getArguments();
            if (args != null){
                this.player = args.getParcelable(ARG_PLAYERS);
            }
            if (player == null){
                throw new IllegalArgumentException("Player list can not be null");
            }
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            return inflater.inflate(R.layout.fragment_player, container, false);
        }

        @Override
        public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            ((TextView)view.findViewById(R.id.txt_player)).setText(player.toString());
        }
    }

StatePagerAdapter.java

public class StatePagerAdapter extends FragmentStatePagerAdapter {

    private ArrayList<Player> players;
    private List<String> titles;

    public StatePagerAdapter(FragmentManager fm, ArrayList<Player> players, List<String> titles) {
        super(fm);
        if (players.size() != titles.size())
            throw new IllegalArgumentException("Sizes must be equal");
        this.players = players;
        this.titles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        return PlayerFragment.newInstance(players.get(position));
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }
}

MainActivity.java

public class MainActivity extends AppCompatActivity {

    ViewPager viewPager;

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

        ArrayList<Player> players = new ArrayList<>();
        players.add(new Player("a", 1));
        players.add(new Player("b", 2));
        players.add(new Player("c", 3));

        List<String> titles = new ArrayList<>(Arrays.asList("Title1", "Title2", "Title3"));

        StatePagerAdapter adapter = new StatePagerAdapter(getSupportFragmentManager(), players, titles);

        viewPager = findViewById(R.id.view_pager);

        viewPager.setAdapter(adapter);
    }
}

上一篇:

您能否请分享您的PlayersFragment课程并尝试以下代码。

@Override
public android.support.v4.app.Fragment getItem(int position) {
    Fragment player_fragment = new PlayerFragment();
    Bundle bundle = new Bundle();
    bundle.putString("player_position_string", player_list.get(position));
    player_fragment.setArguments(bundle);
    return player_fragment;
}