I am trying to make listener interface between two activities Act1 and Act2
. Act1
will start Act2
. If there is some event occurred in Act2
, it will inform it to Act1
. Problem is that I am starting new activity using Intent, so how Act1 will assign itself as listener to Act2’s interface?
Act1.java
public class Act1 extends ActionBarActivity implements ActionBar.OnNavigationListener { ActionBar actionbar; Intent pizzaIntent; boolean visibleFirstTime = true; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.menutab); //set actionbar here } @Override public boolean onNavigationItemSelected(int arg0, long arg1)// item pos, // itemid { switch (arg0) { case 0: if(this.visibleFirstTime == false) { if(pizzaIntent == null) { pizzaIntent = new Intent(this,Act2.class); //how to call setChangeListener? } startActivity(pizzaIntent); } else this.visibleFirstTime = false; break; case 1: System.out.println("selected: " + arg0); break; case 2: System.out.println("selected: " + arg0); break; case 3: System.out.println("selected: " + arg0); break; default: break; } return true; } }
Act2.java
public class Act2 extends Activity { selectionChangeListener listener; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pizza_slice_selection); } public void setChangeListener(selectionChangeListener listener) { this.listener = listener; } private interface selectionChangeListener { public void selectionMadeAtIndex(int index); } }
Note: Please don’t suggest me to use fragments. I want to use activities currently.
Advertisement
Answer
Have you considered using LocalBroadcastManager?
In Act1’s onCreate:
act2InitReceiver= new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // do your listener event stuff } }; LocalBroadcastManager.getInstance(this).registerReceiver(act2InitReceiver, new IntentFilter("activity-2-initialized"));
In Act1’s onDestroy:
LocalBroadcastManager.getInstance(this).unregisterReceiver(act2InitReceiver);
In Act2’s onCreate:
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("activity-2-initialized"));
Give me a comment if the code doesn’t compile, I’m writing it by hand.