簡體   English   中英

將數據從 Activity 移動到另一個 Activity 的 TabFragment 的 Fragment

[英]Moving Data from Activity to Another Activity's TabFragment's Fragment

我想將一些數據從我的 Mainactivity 移動到一個 Fragment ......它位於一個選項卡片段(處理 SectionPagerAdapter)內......它位於 Mainactivity2 的一個片段內。

我覺得它太復雜了,無法完成。

GameEndedActivity (查看wrongcorrect的變量...這些將被轉移)

 public class GameEndedActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game_ended); int correct = getIntent().getIntExtra("correct", 0); int wrong = getIntent().getIntExtra("wrong", 0); } }

標簽片段

 public class TabFragment extends Fragment { private int tabsCount; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_tab, container, false); if(this.getContext() instanceof ChallengeOverviewActivity){ tabsCount = 2; } else { tabsCount = 3; } SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this.getContext(), getFragmentManager(), tabsCount); ViewPager viewPager = view.findViewById(R.id.view_pager); viewPager.setAdapter(sectionsPagerAdapter); TabLayout tabs = view.findViewById(R.id.tabs); tabs.setupWithViewPager(viewPager); return view; } }

ResultFragment (在此處傳輸數據 - 錯誤和正確的變量)

 public class ResultDetailsFragment extends Fragment { private TextView tvWrong, tvCorrect; private AnswerListener answerListener; public interface AnswerListener { public void correct(int i); public void wrong(int i); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_result_details, container, false); tvCorrect = view.findViewById(R.id.tvCorrect); tvWrong = view.findViewById(R.id.tvWrong); return view; } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); if (context;= null) { answerListener = (AnswerListener) context; } } }

一種方法是在創建片段實例時將 arguments 添加到片段中。 在您創建要附加的片段的活動中,向其中添加一些 arguments。 然后可以從片段 onCreate 方法訪問這些 arguments。

當您在片段中並創建第二個片段時,只需再次執行相同的操作即可。

檢查這個答案,它更詳細地解釋了如何做到這一點: https://stackoverflow.com/a/17436739/964887

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM