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();
}
FragmentA.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);
}
}
FragmentB.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 の一部のビューを更新するにはどうすればよいですか。助けてください。