问题描述
我正在尝试在两个活动 Act1 和 Act2
之间创建侦听器接口.Act1
将启动 Act2
.如果Act2
有事件发生,它会通知Act1
.问题是我正在使用 Intent 启动新活动,那么 Act1 如何将自己指定为 Act2 界面的侦听器?
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.
推荐答案
您是否考虑过使用 LocalBroadcastManager?
在 Act1 的 onCreate 中:
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"));
在 Act1 的 onDestroy 中:
In Act1's onDestroy:
LocalBroadcastManager.getInstance(this).unregisterReceiver(act2InitReceiver);
在 Act2 的 onCreate 中:
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.
这篇关于如何使用接口在两个活动之间进行通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!