MainActivity.java
FragmentA fragmentA = null;
FragmentB fragmentB = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
public void replaceFragment(Fragment newFragment){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.right_container, newFragment);
ft.addToBackStack(null);
ft.commit();
}
public void removeFromActivity(Fragment oldFrag){
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
manager.popBackStack();
manager.executePendingTransactions();
ft.remove(oldFrag);
ft.commit();
}
片段A.java
public class FragmentA extends Fragment implements OnClickListener{
public View contentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(null == contentView){
contentView = inflater.inflate(R.layout.fragment_a, null);
EditText editTxt = (EditText) contentView.findViewById(R.id.right_frag_edit_txt);
editTxt.setOnClickListener(this);
}
//--------------------------------------------------//
//Here If I am printing
EditText editTxt = (EditText) contentView.findViewById(R.id.right_frag_edit_txt);
System.out.println(editTxt.getText()); //Output -- Now Button has Clicked --New value as expected
return contentView;
}
public void setValues(String newVal){
EditText editTxt = (EditText) contentView.findViewById(R.id.right_frag_edit_txt);
editTxt.setText(newVal);
}
@Override
public void onClick(View v) {
FragmentB newFrag = new FragmentB();
((MainActivity)getActivity()).fragmentB = newFrag;
((MainActivity)getActivity()).replaceFragment(newFrag);
}
}
片段B.java
public class ReplacedFragment extends Fragment implements OnItemClickListener{
public View contentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(null == contentView){
contentView = inflater.inflate(R.layout.fragment_b, null);
}
return contentView;
}
@Override
public void onClick(View v) {
FragmentA previousFrag = ((MainActivity)getActivity()).fragmentA;
previousFrag.setValues("Now Button has Clicked");
((MainActivity)getActivity()).removeFromActivity(this);
}
}
当我单击“返回”按钮时,从 fragmentB 中,我只是从返回堆栈中删除了这个片段。结果 FragmentB 恢复回来。但是 edittext 值没有用新值更新。
当 FragmentA 恢复时,我应该怎么做才能更新它的某些视图。请帮忙。