通过FragmentStateAdapter将数据从Activity传递到Fragment

3htmauhk  于 2023-11-19  发布在  Android
关注(0)|答案(2)|浏览(129)

我目前正在为一个评分助手应用程序的个人项目应用程序。目的是使用该应用程序来跟踪每个球员的积分,并获得高分和其他花哨的功能。
现在,我有一个使用ViewPager2的Tabbed Activity。对于那些熟悉它的人来说,你会比我知道得更多,但我注意到的是,我从来没有在Activity中示例化我的Fragment类,只在FragmentStateAdapter中示例化。在我的Activity中,我只使用两个选项卡,一个用于游戏方面,一个用于积分显示。记住这一点,我的活动类是这样的:

八孔活动.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();
    }
}

字符串
正如你所看到的,我有一个RoomDatabase,我用它来存储应用程序中的数据。当我通过Intent启动这个Activity时,我传递了正在玩的游戏的ID。这就是我遇到问题的地方。

我想做的事:

我想把从intent.getLongExtra("GameID", 0)得到的变量gameID一直传递给EightHoleScoresFragment类。
我在使用BundleputParcelableArrayList()方面没有什么运气
下面是我使用的其他类。注意,Participants.java类是我想用gameID变量提取的。

参与者.java

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);
    }
}

EightHolePagerAdapter.java

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;
    }
}

EightHoleScoresFragment.java

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;
    }
}


我为代码的摘要量道歉。我觉得这一切都是必要的,能够理解发生了什么。我已经尝试使用Bundle,正如我所说的,我想知道是否有可能直接将Intent的内容传递给EightHoleScoresFragment,并使用一个方法链接回父EightHoleActivity,我不确定...
提前感谢!

57hvy0tb

57hvy0tb1#

请尝试这种方法
活动中:
将gameId作为额外参数传递并在Adapter中接收

viewPager2.setAdapter(new EightHolePagerAdapter(this, gameID));

字符串
在ViewPagerAdapter中:
EightHoleScoresFragment获取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);
    }
}

t1qtbnec

t1qtbnec2#

有一种简单得多的方法可以做到这一点,Rajasekhar的答案当然是“正确”的方法.

EightHoleActivity.java这会将变量导入适配器。

viewPager2.setAdapter(new EightHolePagerAdapter(this, gameID));

字符串

EightHolePagerAdapter一旦它在你的适配器中.

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.sendVariable(gameId);
        }
    }

    @Override
    public int getItemCount() {
        return 2;
    }
}

EightHoleScoresFragment此时只需设置一个静态变量即可完成,不需要创建bundle,也不需要从bundle中检索数据,因为数据已经存在。

public class EightHoleScoresFragment extends Fragment {

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

    public static EightHoleScoresFragment sendVariable(long gameId) {
        EightHoleScoresFragment fragment = new EightHoleScoresFragment();
        gameId2 = gameId;
        return fragment;
    }

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

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

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


这样就可以了。不需要Bundle或Arguments。少了几行代码。我想说拥有一个bundle对于将分数移动到其他地方是很有用的.但是只要你只需要将数据从一个Activity移动到一个片段,那么.一旦它进入适配器.你就完成了。

相关问题