Search code examples
javaandroidsaveonclicklistenerparcelable

can write OnClickListener into parceable?


Hello I have a trouble with OnClickListener

View.OnClickListener listener= new View.OnClickListener() 
{ 
@Override 
public void onClick(View view) 
   { 
     Toast.makeText(Conversations.this, "click on  MSG", 
           Toast.LENGTH_SHORT).show(); 
  } 
};

========================================================================

I Need put this listener into Fragment which will parceable. I not parceableing listener but after readvalue is null and when click app crasher because it's reference on null object.

now I need find some methods which can use for save and read object (View.OnClickListener) if parceable or something similar. Without this I need rebuild my project :(

Please Help me.

Thanks

_______________________________________________________--

I haven't have fragment in fragment I want all fragment put into "extra" and in other activity read from extra..

Intent i= new Intent(Conversations.this,MessagesSingleFragmentActivity.cla‌​ss); i.putExtra("Fragment1", (Parcelable) recycleMessage); startActivity(i);

and in other activity have

Intent extras = getIntent(); Fragment fragment = (Fragment) extras.getParcelableExtra("Fragment1"); fm.beginTransaction().replace(R.id.fragment_container, fragment).commit();

Solution

  • No you cannot pass OnClickListener as Parcelable but , if you want to observe click from one fragment to another , then you have to implement the onclick in second fragment.

    FragA.java:// who have onClickListener

    Runnable run;
    
    public void setClick(Runnable run){
       this.run = run;
    }
    
    view.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            // do something in onclick
            if(run!=null){run.run();}
        }
    });
    

    FragB.java:

    ((FragA)getParentFragment()).setClick(
           new Runnable() {
                @Override
                public void run() {
                    // do something in other fragment
                }
            }
    )
    

    Updated:

    If you want to perform something onClick of ActivityA on ActivityB , then EventBus are best options for that use Otto or EventBus by GreenBot