我想通過單擊界面按鈕將變量從當前片段返回到上一個片段。我無法從從 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();

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
使用視圖模型。ViewModel是一個用于存儲和管理UI相關數據的類。它是 Android Jetpack 的一部分。因此,通過使用 ViewModel,即使應用程序的 UI 發生變化,您的應用程序也會獲得一些一致的數據。
添加回答
舉報
0/150
提交
取消