[英]How can I access a method from an activity and use it into another activity in Android?
我有第一堂课叫iHave
public class iHave extends ActionBarActivity
{
//below is the instance for calling the method from the other activity.
(The name of the other activity is **iThank**)
**iThank thankYou = new iThank();**
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_have);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
**//this is the method I want to access from iThank class** **strong text**
thankYou.display();
}
});
}
//下一个类是“ iThank”
public class iThank extends ActionBarActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_i_thank);
txtThank = (TextView) findViewById(R.id.textView3);
//this is the method I want to access/use from iHave Activity
public void display()
{
txtThank.setText ("Shine");
}
}
如何将iThank活动的“ public void display()
”方法用于“ iHave”活动? 它总是给我一个NullPointerException
错误。 请帮忙。 非常感谢你!
如何从活动中访问方法并将其用于Android中的另一个活动?
通过创建对象以供其他人从Activity访问方法是正确的方法。
使用LocalBroadcastManager在应用程序组件之间进行通信。
1.在按钮上单击,从iHave
发送广播:
@Override
public void onClick(View v)
{
Intent intent = new Intent("DISPLAY_EVENT");
LocalBroadcastManager.getInstance(v.getContext()).sendBroadcast(intent);
}
2.在iThank
活动中注册LocalBroadcastManager
:
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(ReceiveMessage,
new IntentFilter("DISPLAY_EVENT"));
}
3.在iThank
Activity中创建BroadcastReceiver
对象并调用display()方法:
private BroadcastReceiver ReceiveMessage = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
display();
}
};
还要在TextView的显示方法中添加null检查:
public void display()
{
if(txtThank !=null)
txtThank.setText ("Shine");
}
请不要这样做,这不是活动的工作方式。 您可能需要查看《 活动开发人员指南》以开始使用。 如果要从当前前台活动(例如iHave
)启动新活动(例如iThank
),则永远不要自己直接实例化该类,而始终 使用intent启动它 。 如果您有数据要传递(例如要显示的消息),则需要将其与意图捆绑在一起(请参阅同一链接)。
活动永远不要直接在彼此之间调用方法,因为这要求它们之间具有相互引用。 该框架独立管理每个活动的生命周期,这些引用可能导致泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.