简体   繁体   中英

Android fragment communication

i would like to have communication between fragments in sliding menu but in my code getFragmentManager().findFragmentByTag returns null. I've searched and noticed i have to use executePendingTransactions() after commit() (if i'm right) . but i got this error :

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

i am using android.app.Fragment not support package . please help me.

this is my mainActivity code:

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 code:

   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 code:

    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();

}

As per the documentation of FragmentTransaction, commit method:

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.

Here you are trying to do findFragmentByTag immediately after commit and transaction might not have been committed by then. So in the current scenario, if you will give some wait before it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM