当前位置: 首页 > 知识库问答 >
问题:

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

督阿苏
2023-03-14
            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);
}

这是我的适配器类。

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时,我传递了不同的arraylist,当调用get item时,我从arraylist中获取条目并将其作为参数传递给该片段,但当我运行此操作时,我最初只获得所有参数,当我更改选项卡时不会发生任何事情。我试着调试,发现getitem最初只被调用了8次,当我改变viewpager选项卡时,什么也不会发生。我也尝试了fragment newinstance方法和addonpagechangelistener,但得到了相同的结果。请帮忙。

这是我的玩家碎片类。

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个答案

戴高远
2023-03-14

编辑:

我添加了一个工作演示。请你检查一下这个,让我知道它是否有效。

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);
    }
}
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);
    }
}
@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;
}
 类似资料:
  • 试图在Spring中学习MVC的基础知识(我只使用Spring构建RESTAPI),但我很难理解如何将新数据返回到同一个视图,似乎我有很多重复的代码,HTML页面完全依赖于th:if语句。。。 发出POST请求,然后用新的/更新的数据加载同一ModelAndView的最佳方式是什么?代码如下: 控制器: 欢迎html:

  • 问题内容: 设法获得logstash(1.3.1)以将数据发送到elasticsearch(0.9.5)。 我的logstash conf文件设置是 数据存储在ES中的索引logstash-2013.12.xx下 但是,如果我重新启动logstash,请说第二天-将相同的数据重新加载到新索引中。即使我再次重新启动,索引中的文档计数也会加倍。 好像logstash重新读取数据,ES也在复制文档。 有

  • 问题内容: 我的.routing.ts文件中有这个 我的文件检查id参数并相应地加载数据。在路由器的早期版本中,如果我从/ page / 4转到/ page / 25,则该页面将“重新加载”并且组件将更新。 现在,当我尝试导航到/ page / X时,其中X是id,它只会第一次加载,然后url会更改,但是组件不会再次“重新加载”。 是否需要传递某些内容以强制重新加载组件并调用ngOnInit事件?

  • 我使用了和。 但它一次加载两个页面。 有什么方法可以在viewpager中只加载一个页面吗?

  • 编辑:最后一个问题,如何通过值而不是引用来存储它?

  • 我是android的初学者。我用两个片段制作了一个视图寻呼机。我在第一个片段中有一些回收器视图项。一个回收器视图项将填充一个片段。在滑动到下一个片段时,我可以加载我已滑动的回收器视图项的详细信息吗?或者如何在滑动时将回收器视图项的位置传递到下一个片段,请提供帮助。