我试图在两个活动之间建立监听器接口Act1 and Act2。Act1将开始Act2。如果发生了某些事件Act2,它将通知它Act1。问题是我正在使用Intent开始新活动,那么Act1如何将自己分配为Act2接口的侦听器?
Act1 and Act2
Act1
Act2
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); } }
注意: 请不要建议我使用片段。我现在要使用活动。
您是否考虑过使用LocalBroadcastManager?
在Act1的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"));
在Act1的onDestroy中:
LocalBroadcastManager.getInstance(this).unregisterReceiver(act2InitReceiver);
在Act2的onCreate中:
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent("activity-2-initialized"));
如果代码无法编译,请给我评论,我是手工编写的。