Java 通过FragmentStateAdapter将数据从活动传递到片段

Java 通过FragmentStateAdapter将数据从活动传递到片段,java,android,android-fragments,android-activity,bundle,Java,Android,Android Fragments,Android Activity,Bundle,我目前正在为一个计分助手应用程序开发个人项目应用程序。其目的是使用该应用程序跟踪每位玩家的积分,并拥有高分和其他奇特功能 现在,我有一个选项卡式活动,它使用ViewPager2。对于那些熟悉它的人,你会比我知道更多,但我注意到我从未在活动中实例化我的Fragment类,只是在FragmentStateAdapter中。在我的活动中,我只使用两个选项卡,一个用于游戏方面,另一个用于积分显示。考虑到这一点,我的活动类如下所示: EightHoleActivity.java package com.e

我目前正在为一个计分助手应用程序开发个人项目应用程序。其目的是使用该应用程序跟踪每位玩家的积分,并拥有高分和其他奇特功能

现在,我有一个选项卡式活动,它使用
ViewPager2
。对于那些熟悉它的人,你会比我知道更多,但我注意到我从未在活动中实例化我的
Fragment
类,只是在
FragmentStateAdapter
中。在我的活动中,我只使用两个选项卡,一个用于游戏方面,另一个用于积分显示。考虑到这一点,我的活动类如下所示:

EightHoleActivity.java

package com.example.game;

import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

public class EightHoleActivity extends AppCompatActivity {

    private long gameID;
    private RoomDB database;

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

        Intent intent = getIntent();
        gameID = intent.getLongExtra("GameID", 0);
        database = RoomDB.getInstance(EightHoleActivity.this);

        ViewPager2 viewPager2 = findViewById(R.id.eight_hole_view_pager);
        viewPager2.setAdapter(new EightHolePagerAdapter(this));
        TabLayout tabLayout = findViewById(R.id.eight_hole_tabs);
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(
                tabLayout, viewPager2, (tab, position) -> {
                    switch (position){
                        case 0: {
                            tab.setText("Current game");
                            tab.setIcon(R.drawable.ic_twotone_games_24);
                            break;
                        }
                        default: {
                            tab.setText("Scores");
                            tab.setIcon(R.drawable.ic_baseline_list_24);
                            break;
                        }
                    }
                }
        );
        tabLayoutMediator.attach();
    }
}
package com.example.game;

import android.os.Parcel;
import android.os.Parcelable;

import androidx.annotation.Nullable;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;

import java.util.Objects;

@Entity(tableName = "participants", foreignKeys = {
        @ForeignKey(entity = Player.class, parentColumns = "id", childColumns = "player_id", onDelete = ForeignKey.CASCADE),
        @ForeignKey(entity = Game.class, parentColumns = "id", childColumns = "game_id", onDelete = ForeignKey.CASCADE)})
public class Participant implements Parcelable {
    @PrimaryKey(autoGenerate = true)
    private long id;

    @ColumnInfo(name = "player_id", index = true)
    private long playerID;

    @ColumnInfo(name = "game_id", index = true)
    private long gameID;

    @ColumnInfo(name = "score")
    private int score;

    protected Participant(Parcel in) {
        id = in.readLong();
        playerID = in.readLong();
        gameID = in.readLong();
        score = in.readInt();
    }

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

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

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getPlayerID() {
        return playerID;
    }

    public void setPlayerID(long playerID) {
        this.playerID = playerID;
    }

    public long getGameID() {
        return gameID;
    }

    public void setGameID(long gameID) {
        this.gameID = gameID;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public Participant(long playerID, long gameID){
        this.playerID = playerID;
        this.gameID = gameID;
    }

    @Override
    public boolean equals(@Nullable Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Participant)) return false;

        Participant participant = (Participant) obj;
        if (id != participant.id) return false;
        return Objects.equals(score, participant.score) || Objects.equals(playerID, participant.playerID) || Objects.equals(gameID, participant.gameID);
    }

    @Override
    public int hashCode() {
        int result = (int) id;
        result = (int) (31 * result + playerID + gameID + score);
        return result;
    }

    @Override
    public String toString() {
        return "Participant{" +
                "ID=" + id +
                ", PlayerID='" + playerID + '\'' +
                ", GameID='" + gameID + '\'' +
                ", Score='" + score + '\'' +
                '}';
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeLong(playerID);
        dest.writeLong(gameID);
        dest.writeInt(score);
    }
}
package com.example.game;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

public class EightHolePagerAdapter extends FragmentStateAdapter {

    public EightHolePagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position){
            case 0:
                return new EightHoleGameFragment();
            default:
                return new EightHoleScoresFragment();
        }
    }

    @Override
    public int getItemCount() {
        return 2;
    }
}
package com.example.game;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;

public class EightHoleScoresFragment extends Fragment {

    private ArrayList<Participant> participants = new ArrayList<Participant>();

    public EightHoleScoresFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_eight_hole_scores, container, false);
        ListView listView = (ListView) view.findViewById(R.id.eight_hole_current_scores_list);

        ScoresAdapter adapter = new ScoresAdapter(getActivity(), R.layout.scores_adapter_layout, participants);
        listView.setAdapter(adapter);
        return view;
    }
}
如您所见,我有一个
RoomDatabase
,用于在应用程序中存储数据。当我通过意图启动此活动时,我传递正在玩的游戏的
ID
。这就是我的问题所在

我想做什么:

我想将从
intent.getLongExtra(“gameID”,0)
获得的变量
gameID
一直传递到
EightHoleScoresFragment

使用
Bundle
putParcelableArrayList()

下面是我使用的其他类。 请注意,class Participants.java是我想用
gameID
变量提取的内容

Participants.java

package com.example.game;

import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

public class EightHoleActivity extends AppCompatActivity {

    private long gameID;
    private RoomDB database;

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

        Intent intent = getIntent();
        gameID = intent.getLongExtra("GameID", 0);
        database = RoomDB.getInstance(EightHoleActivity.this);

        ViewPager2 viewPager2 = findViewById(R.id.eight_hole_view_pager);
        viewPager2.setAdapter(new EightHolePagerAdapter(this));
        TabLayout tabLayout = findViewById(R.id.eight_hole_tabs);
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(
                tabLayout, viewPager2, (tab, position) -> {
                    switch (position){
                        case 0: {
                            tab.setText("Current game");
                            tab.setIcon(R.drawable.ic_twotone_games_24);
                            break;
                        }
                        default: {
                            tab.setText("Scores");
                            tab.setIcon(R.drawable.ic_baseline_list_24);
                            break;
                        }
                    }
                }
        );
        tabLayoutMediator.attach();
    }
}
package com.example.game;

import android.os.Parcel;
import android.os.Parcelable;

import androidx.annotation.Nullable;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;

import java.util.Objects;

@Entity(tableName = "participants", foreignKeys = {
        @ForeignKey(entity = Player.class, parentColumns = "id", childColumns = "player_id", onDelete = ForeignKey.CASCADE),
        @ForeignKey(entity = Game.class, parentColumns = "id", childColumns = "game_id", onDelete = ForeignKey.CASCADE)})
public class Participant implements Parcelable {
    @PrimaryKey(autoGenerate = true)
    private long id;

    @ColumnInfo(name = "player_id", index = true)
    private long playerID;

    @ColumnInfo(name = "game_id", index = true)
    private long gameID;

    @ColumnInfo(name = "score")
    private int score;

    protected Participant(Parcel in) {
        id = in.readLong();
        playerID = in.readLong();
        gameID = in.readLong();
        score = in.readInt();
    }

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

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

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getPlayerID() {
        return playerID;
    }

    public void setPlayerID(long playerID) {
        this.playerID = playerID;
    }

    public long getGameID() {
        return gameID;
    }

    public void setGameID(long gameID) {
        this.gameID = gameID;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public Participant(long playerID, long gameID){
        this.playerID = playerID;
        this.gameID = gameID;
    }

    @Override
    public boolean equals(@Nullable Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Participant)) return false;

        Participant participant = (Participant) obj;
        if (id != participant.id) return false;
        return Objects.equals(score, participant.score) || Objects.equals(playerID, participant.playerID) || Objects.equals(gameID, participant.gameID);
    }

    @Override
    public int hashCode() {
        int result = (int) id;
        result = (int) (31 * result + playerID + gameID + score);
        return result;
    }

    @Override
    public String toString() {
        return "Participant{" +
                "ID=" + id +
                ", PlayerID='" + playerID + '\'' +
                ", GameID='" + gameID + '\'' +
                ", Score='" + score + '\'' +
                '}';
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeLong(playerID);
        dest.writeLong(gameID);
        dest.writeInt(score);
    }
}
package com.example.game;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

public class EightHolePagerAdapter extends FragmentStateAdapter {

    public EightHolePagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position){
            case 0:
                return new EightHoleGameFragment();
            default:
                return new EightHoleScoresFragment();
        }
    }

    @Override
    public int getItemCount() {
        return 2;
    }
}
package com.example.game;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;

public class EightHoleScoresFragment extends Fragment {

    private ArrayList<Participant> participants = new ArrayList<Participant>();

    public EightHoleScoresFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_eight_hole_scores, container, false);
        ListView listView = (ListView) view.findViewById(R.id.eight_hole_current_scores_list);

        ScoresAdapter adapter = new ScoresAdapter(getActivity(), R.layout.scores_adapter_layout, participants);
        listView.setAdapter(adapter);
        return view;
    }
}
EightHoleScoresFragment.java

package com.example.game;

import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

public class EightHoleActivity extends AppCompatActivity {

    private long gameID;
    private RoomDB database;

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

        Intent intent = getIntent();
        gameID = intent.getLongExtra("GameID", 0);
        database = RoomDB.getInstance(EightHoleActivity.this);

        ViewPager2 viewPager2 = findViewById(R.id.eight_hole_view_pager);
        viewPager2.setAdapter(new EightHolePagerAdapter(this));
        TabLayout tabLayout = findViewById(R.id.eight_hole_tabs);
        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(
                tabLayout, viewPager2, (tab, position) -> {
                    switch (position){
                        case 0: {
                            tab.setText("Current game");
                            tab.setIcon(R.drawable.ic_twotone_games_24);
                            break;
                        }
                        default: {
                            tab.setText("Scores");
                            tab.setIcon(R.drawable.ic_baseline_list_24);
                            break;
                        }
                    }
                }
        );
        tabLayoutMediator.attach();
    }
}
package com.example.game;

import android.os.Parcel;
import android.os.Parcelable;

import androidx.annotation.Nullable;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.ForeignKey;
import androidx.room.PrimaryKey;

import java.util.Objects;

@Entity(tableName = "participants", foreignKeys = {
        @ForeignKey(entity = Player.class, parentColumns = "id", childColumns = "player_id", onDelete = ForeignKey.CASCADE),
        @ForeignKey(entity = Game.class, parentColumns = "id", childColumns = "game_id", onDelete = ForeignKey.CASCADE)})
public class Participant implements Parcelable {
    @PrimaryKey(autoGenerate = true)
    private long id;

    @ColumnInfo(name = "player_id", index = true)
    private long playerID;

    @ColumnInfo(name = "game_id", index = true)
    private long gameID;

    @ColumnInfo(name = "score")
    private int score;

    protected Participant(Parcel in) {
        id = in.readLong();
        playerID = in.readLong();
        gameID = in.readLong();
        score = in.readInt();
    }

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

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

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getPlayerID() {
        return playerID;
    }

    public void setPlayerID(long playerID) {
        this.playerID = playerID;
    }

    public long getGameID() {
        return gameID;
    }

    public void setGameID(long gameID) {
        this.gameID = gameID;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public Participant(long playerID, long gameID){
        this.playerID = playerID;
        this.gameID = gameID;
    }

    @Override
    public boolean equals(@Nullable Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Participant)) return false;

        Participant participant = (Participant) obj;
        if (id != participant.id) return false;
        return Objects.equals(score, participant.score) || Objects.equals(playerID, participant.playerID) || Objects.equals(gameID, participant.gameID);
    }

    @Override
    public int hashCode() {
        int result = (int) id;
        result = (int) (31 * result + playerID + gameID + score);
        return result;
    }

    @Override
    public String toString() {
        return "Participant{" +
                "ID=" + id +
                ", PlayerID='" + playerID + '\'' +
                ", GameID='" + gameID + '\'' +
                ", Score='" + score + '\'' +
                '}';
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeLong(id);
        dest.writeLong(playerID);
        dest.writeLong(gameID);
        dest.writeInt(score);
    }
}
package com.example.game;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;

public class EightHolePagerAdapter extends FragmentStateAdapter {

    public EightHolePagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position){
            case 0:
                return new EightHoleGameFragment();
            default:
                return new EightHoleScoresFragment();
        }
    }

    @Override
    public int getItemCount() {
        return 2;
    }
}
package com.example.game;

import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import java.util.ArrayList;

public class EightHoleScoresFragment extends Fragment {

    private ArrayList<Participant> participants = new ArrayList<Participant>();

    public EightHoleScoresFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_eight_hole_scores, container, false);
        ListView listView = (ListView) view.findViewById(R.id.eight_hole_current_scores_list);

        ScoresAdapter adapter = new ScoresAdapter(getActivity(), R.layout.scores_adapter_layout, participants);
        listView.setAdapter(adapter);
        return view;
    }
}
package com.example.game;
导入android.os.Bundle;
导入androidx.fragment.app.fragment;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.ListView;
导入java.util.ArrayList;
公共类EightHoleScoresFragment扩展了片段{
私有ArrayList参与者=新建ArrayList();
公共八人组成员(){
}
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图=充气机。充气(R.layout.fragment\u八孔\u分数,容器,错误);
ListView=(ListView)view.findViewById(R.id.eight\u hole\u current\u scores\u list);
ScoresAdapter=新的ScoresAdapter(getActivity(),R.layout.scores\u adapter\u layout,参与者);
setAdapter(适配器);
返回视图;
}
}
很抱歉代码太多了。我觉得有必要了解发生了什么。正如我所说,我曾尝试使用
捆绑包
,在网站上给出了各种答案,但都没有奏效。我想知道是否有可能直接将意图的内容传递给
EightHoleScoresFragment
,方法是链接回父级
EightHoleActivity
,但我不确定


提前谢谢

请尝试这种方法

在活动中:

将gameId作为额外参数传递并在适配器中接收

viewPager2.setAdapter(new EightHolePagerAdapter(this, gameID));
在ViewPagerAdapter中:

EightholeCoresFragment
获取gameId并调用fragment newInstance

public class EightHolePagerAdapter extends FragmentStateAdapter {

    private long gameId;

    public EightHolePagerAdapter(@NonNull FragmentActivity fragmentActivity, long gameId) {
        super(fragmentActivity);
        this.gameId = gameId;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        switch (position){
            case 0:
                return new EightHoleGameFragment();
            default:
                return EightHoleScoresFragment.newInstance(gameId);
        }
    }

    @Override
    public int getItemCount() {
        return 2;
    }
}
在你的片段中:

以这种方式接收片段中的gameId参数

public class EightHoleScoresFragment extends Fragment {

    private static final String ARG_GAME_ID = "game_id";
    private long mGameId;

    public static EightHoleScoresFragment newInstance(long gameId) {
        EightHoleScoresFragment fragment = new EightHoleScoresFragment();
        Bundle args = new Bundle();
        args.putLong(ARG_GAME_ID, gameId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mGameId = getArguments().getLong(ARG_GAME_ID);
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Log.d("EightHoleScoresFragment", "Game Id = " + mGameId);
    }
}

我已经添加了我的答案,一旦尝试了这种方法。效果很好,我唯一需要更改的是删除
EightHoleScoresFragment.newInstance(gameId)
之前的
new
关键字。我在编辑Java代码时打开了我的kotlin项目。我没有发现要移除的。我无论如何都会编辑它。