2017-01-19 14 views
0

たとえば、1つの整数変数と1つのTextViewを含む2つのフラグメントがあります。それらの1つにボタンがあります。私はこのボタンを使って、他のフラグメントを含むすべての整数とTextViewを変更します。他のフラグメントのVariableとTextViewにはどうすればアクセスできますか?サンプルコードで説明してください。他のフラグメント変数または要素へのアクセス

答えて

1

フラグメント間通信は、基本的に、フラグメントをホストし、フラグメントAにインターフェイスを定義し、そのインターフェイスを実装するアクティビティを介して行われます。これで、Fragmentのインターフェースメソッドを呼び出すことができ、アクティビティはイベントを受け取ります。あなたのアクティビティでは、受け取った値でテキストビュー(例えば)を更新するために、2番目のフラグメントを呼び出すことができます:

// You Activity implements your interface which is defined in FragmentA 
public class YourActivity implements FragmentA.TextClicked{ 
    @Override 
    public void sendText(String text){ 
     // Get instance of Fragment B using FragmentManager 
     FraB frag = (FragB) 
      getSupportFragmentManager().findFragmentById(R.id.fragment_b); 
     frag.updateText(text); 
    } 
} 


// Fragment A defines an Interface, and calls the method when needed 
public class FragA extends Fragment{ 

    TextClicked mCallback; 

    public interface TextClicked{ 
     public void sendText(String text); 
    } 

    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 

     // This makes sure that the container activity has implemented 
     // the callback interface. If not, it throws an exception 
     try { 
      mCallback = (TextClicked) activity; 
     } catch (ClassCastException e) { 
      throw new ClassCastException(activity.toString() 
       + " must implement TextClicked"); 
     } 
    } 

    public void someMethod(){ 
     mCallback.sendText("YOUR TEXT"); 
    } 

    @Override 
    public void onDetach() { 
     mCallback = null; // => avoid leaking 
     super.onDetach(); 
    } 
} 

// Fragment B has a public method to do something with the text 
public class FragB extends Fragment{ 

    public void updateText(String text){ 
     // Here you have it 
    } 
} 
関連する問題