2017-05-29 121 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()不起作用。 –