2017-05-29 118 views
0

我想在滑動菜單中的片段之間進行通信,但在我的代碼getFragmentManager().findFragmentByTag中返回null。 我搜索並注意到我必須在commit()之後使用executePendingTransactions()(如果我是對的)。 但我得到這個錯誤:Android片段通信

529-529/info.androidhive.slidingmenu E/AndroidRuntime﹕ FATAL EXCEPTION: main 
Process: info.androidhive.slidingmenu, PID: 529 
java.lang.IllegalStateException: Recursive entry to executePendingTransactions 

我使用android.app.Fragment沒有support package。 請幫助我。

這是我的mainActivity代碼:

FragmentManager fm = MainActivity.this.getFragmentManager(); 
FragmentTransaction ft = fm.beginTransaction(); 
GoodsFragment gf= new GoodsFragment(); 
ft.replace(R.id.frame_container, gf, "gf"); 
ft.addToBackStack("gf"); 
ft.commit(); 
fm.executePendingTransactions(); 

gf = (GoodsFragment) getFragmentManager().findFragmentByTag("gf"); 
if(gf != null) 
    { 
     gf.setText(msg); 

    } 
    else 
    { 
     Toast.makeText(this, "Error Sending Message", Toast.LENGTH_SHORT).show(); 
    } 

GoodsFragment代碼:

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    rootView = inflater.inflate(R.layout.fragment_goods, container, false); 
    TextView txtcheckbox = (TextView) rootView.findViewById(R.id.textView1); 
    txtcheckbox.setText("some thing..."); 

    return rootView; } 

void setText(String msg) 
{ 
    TextView mTextView = (TextView) rootView.findViewById(R.id.textView1); 
    mTextView.setText(msg); 
} 

BridgeFragment代碼:

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_bridge, container, false); 

    onButtonClicked(rootView); 
    return rootView; 
} 
    protected void onButtonClicked(View view) 
{ 

    msg ="ghazaleh arabi"; 
    sendMessage(); 
} 

interface StartCommunication 
{ 
    public void setComm(String msg); 
} 

@Override 
public void onAttach(Activity activity) { 

    super.onAttach(activity); 
    if(activity instanceof StartCommunication) 
    { 
     mStartCommunicationListner = (StartCommunication)activity; 
    } 
    else 
     throw new ClassCastException(); 

} 
+0

試試這種方式:Fragment fragment = getFragmentManager()。findFragmentByTag(「gf」); 如果(片段instanceof GoodsFragment){ } –

+0

謝謝,但它再次返回null。我也註釋了這一行fm.executePendingTransactions();執行。 –

+0

你在其他片段內使用片段? –

回答

0

作爲每FragmentTransaction的文檔,commit方法:

Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.

在這裏,您正試圖在提交後立即執行findFragmentByTag,並且事務可能尚未提交。因此,在目前的情況下,如果您需要等一段時間才能開始工作。

+0

所以我怎麼能給它一些等待。我已經使用fm.executePendingTransactions();但是這一行出現錯誤:executePendingTransactions的遞歸入口 –

+0

刪除addToBackStack應該使fm.executePendingTransactions()工作,您可以嘗試讓我知道。 (new Handler())。postDelayed(Runnable r,long delayMillis)' –

+0

我刪除了addToBackStack,但fm.executePendingTransactions()不起作用。 –