在方法中在调用其他activity类中的方法是,出现错误;
错误方法:MainActivity activity=new MainActivity();
错误原因:activity是不能用new来实例化的。
或者有时将Activity中方法写成静态的static, 去调用的,调用之后其它方法也需要改为static,造成修改太大
解决办法:在activity类的onCreate()中 调用该类的构造方法,把context和avtivity对象传过来。话不多说,代码更直观!
1.ClipBoardService.java
public class ClipBoardService { private Context contxt; private MainActivity activity; public Context getContxt() { return contxt; } public void setContxt(Context contxt) { this.contxt = (MainActivity) contxt; } public Activity getActivity() { return (MainActivity) activity; } public void setActivity(Activity activity) { this.activity = (MainActivity) activity; } public ClipBoardService(Context context, MainActivity activity) { this.setContxt(context); this.setActivity(activity); } private void getMethod(){ activity.method(); } }
2.MainActivity.java
public class MainActivity extends Activity{ private ClipBoardService clipBoard; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); clipBoard = new ClipBoardService(this,MainActivity.this); }
public void method(){
} }