我只有一个名为MainActivity的Activity。它有一个必须从另一个类中调用的函数
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void tag_proc(String s1)
{
System.out.println("working i guess"+s1)
}
}
必须从另一个模块中调用此函数
public class NewCls {
MainAcitivity mact= new MainActivity();
public void dothis()
{
String s="new";
mact.tag_proc(s);
}
}
这是不可能的,因为它们处于不同的模块中。什么是最好和最简单的解决方案。如果界面是解决方案,那么如何最好地使用它
答案 0 :(得分:0)
不清楚你想要实现什么但从未这样做过:
MainAcitivity mact= new MainActivity();
您只能通过Intent
创建活动,而非您自己。
如果你想要一个紧密耦合的模块,你只需要在构造函数中传递活动,例如
public NewCls(MainActivity activity) {
myActivityReference = activity
}
public void dothis() {
...
myActivityReference.tag_proc(s);
}
最好是提取一个接口并使用它来代替活动类本身,但为了简单起见,我以简单的方式展示了它。
如果您想要更松散耦合的通信,您可以使用本地广播。只需在活动中注册一个接收器,然后像这样从NewCls发送广播
public void dothis() {
Intent intent = new Intent("custom-event-name");
intent.putExtra("myString", "This is my message!");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
并在您的活动中
@Override
public void onCreate(Bundle savedInstanceState) {
...
// Register to receive messages. We are registering an observer (mMessageReceiver) to receive Intents with actions named "custom-event-name".
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("custom-event-name"));
}
// Our handler for received Intents. This will be called whenever an Intent with an action named "custom-event-name" is broadcasted.
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s1= intent.getStringExtra("myString");
tag_proc(s1);
}
};
@Override
protected void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
答案 1 :(得分:0)
在我看来,这样的调用方法可能是一种不好的做法。您可以将方法设置为静态,但您应该确定这是否适用于此情况。我认为最好的选择可能是使用EventBus,它是有效且具有简单的API。例如:EventBus from greenrobot。