我正在尝试在两个 Activity Act1 and Act2
之间建立监听器接口(interface)。 Act1
将以Act2
开头。如果Act2
中发生了某些事件,它将通知Act1
。问题是我正在使用Intent开始新 Activity ,那么Act1如何将自己分配为Act2接口(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);
}
}
注意:请不要建议我使用片段。我现在要使用 Activity 。
最佳答案
您是否考虑过使用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"));
如果代码无法编译,请给我评论,我是手工编写的。