亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從片段到片段返回變量

從片段到片段返回變量

蝴蝶不菲 2023-07-28 10:06:00
我想通過單擊界面按鈕將變量從當前片段返回到上一個片段。我無法從從 Fragment 類擴展的一個 Fragment 返回變量到從 Fragment 類擴展的另一個 Fragment。但我可以通過接口使用相同的傳輸方法將變量從DialogFragment返回到Fragment。在 MainActivity 中我加載 FirstFragment:getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,                new FirstFragment()).commit();在 FirstFragment onClick TextView tvSecondFragment 類中,我創建片段:class FirstFragment extends Fragment implements SecondFragment.SecondFragmentListener {public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {View view = inflater.inflate(R.layout.first_fragment, container, false);        tvSecondFragment.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Fragment fragment = new SecondFragment();                FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();                fragmentTransaction.add(R.id.fragment_container, fragment);                fragmentTransaction.addToBackStack(null);                fragmentTransaction.commit();            }        });return view;}    @Override    public void sentAge(String input) {        Log.d(TAG, "method sentAge called with variable: " + input);    }}這是 SecondFragment 類,我嘗試在其中返回變量 onClick 按鈕:public class SecondFragment extends Fragment {    private SecondFragmentListener listener;    public interface SecondFragmentListener {        public void sentAge(String input);    }    private EditText editText;    private Button button;    @Nullable    @Override    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {        View view = inflater.inflate(R.layout.second_fragment, container, false);        editText = view.findViewById(R.id.et_age);        button = view.findViewById(R.id.btn_transfer_age);
查看完整描述

2 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

創建您設置的目標片段的實例時SecondFragment:


Fragment fragment = new SecondFragment();

fragment.setTargetFragment(FirstFragment.this, 0);

...

fragmentTransaction.commit();


查看完整回答
反對 回復 2023-07-28
?
慕尼黑8549860

TA貢獻1818條經驗 獲得超11個贊

使用視圖模型。ViewModel是一個用于存儲和管理UI相關數據的類。它是 Android Jetpack 的一部分。因此,通過使用 ViewModel,即使應用程序的 UI 發生變化,您的應用程序也會獲得一些一致的數據。

查看完整回答
反對 回復 2023-07-28
  • 2 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號