2017-02-13 179 views
0

我創建了一個接口,當我按FragmentA上的TextView時,我可以在FragmentB上設置文本。有些東西不起作用,我無法弄清楚這一點。創建一個接口與另一個片段進行通信

我創建了一個接口來調用通訊:

public interface Communicator { 
void respond(String data); 

}

在FragmentA我已經設置TextView的接口上引用名爲Communcator和OnClickListener:

Communicator comm; 

homeTextView.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      comm.respond("Trying to set text on FragmentB from here"); 
     } 
    }); 

FragmentB,設置我的方法來改變文字:

public void setText(final String data) { 
    startTripTxt.setText(data); 
} 

終於在MainActivity我已經實現了接口。我覺得這裏是我做錯了什麼:

@Override 
public void respond(String data) { 

    getSupportFragmentManager().beginTransaction() 
      .replace(R.id.container_main, new FragmentB(), "fragment2").addToBackStack(null).commit(); 

    FragmentB fragmentB= (FragmentB) getSupportFragmentManager().findFragmentByTag("fragment2"); 
    if (fragmentB != null) { 
     fragmentB.setText(data); 
    } 


} 

片段2個負荷,但文字是空的。

+0

好。我認爲這個問題是在MainActivity的響應函數中當你調用'commit()'時,它並沒有在UI線程中運行,需要一段時間才能完成它,然後在之後聲明的fragmentB將爲空。 – TruongHieu

回答

2

碎片2加載,但文本爲空。

你實現了Communicator是可以的,但是你調用FragmentB並傳遞數據的方式並不正確。這就是你無法從FragmentB獲得文本的原因。將數據發送到FragmentB的正確方法應該是這樣的:

public static FragmentB createInstance(String data) { 
     FragmentB fragment = new FragmentB(); 
     Bundle bundle = new Bundle(); 
     bundle.putString("data", data); 
     fragment.setArguments(bundle); 
     return fragment; 
    } 

而且你可以從FragmentB通過得到的數據:

Bundle bundle = getArguments(); 
     if (bundle != null) { 
      String data = bundle.getString("data"); 
     } 
1

它看起來像你聲明fragmentB後,你的意思設置該片段上的文本。你正在調用trainFinderFragment.setText()。這是你的問題嗎?

FragmentB fragmentB= (FragmentB) getSupportFragmentManager().findFragmentByTag("fragment2"); 
if (fragmentB != null) { 
    fragmentB.setText(data); 
} 
+0

我編輯了我的問題。 FragmentB實際上被稱爲TrainFinderFragment,但在此處將其重命名爲FragmentB,因此每個人都更清楚。 – r3dm4n

+0

噢好吧。是的,給你的編輯,你應該採取RoShan的建議。通過一個包傳遞文本。 –