我有第一个类名为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 Activity 的“public void display()
”方法用于“iHave” Activity ?它总是给我一个 NullPointerException
错误。请帮忙。非常感谢!
最佳答案
How can I access a method from an activity and use it into another activity in 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
Activity 中注册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");
}
关于java - 如何从一个 Activity 访问一个方法并将其用于 Android 中的另一个 Activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28523085/