我想通过单击界面按钮将变量从当前片段返回到上一个片段。我无法从从 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);
慕仙森
慕尼黑8549860
相关分类