[英]Android. How to access a class from another file to MainActivity
I created a separate java class called SetIP.java with just a simple print: 我创建了一个单独的Java类SetIP.java,它的打印内容很简单:
package com.myname.appname;
import android.util.Log;
public class SetIP {
public void hello(){
Log.d("System", "Hello World!");
}
}
In the MainActivity I try to call it by: 在MainActivity中,我尝试通过以下方式调用它:
public class MainActivity extends AppCompatActivity {
SetIP setip = new SetIP();
setip.hello();
// OnCreate and Stuff
}
But the error said cannot resolve symbol 'Hello'. 但是出现的错误无法解析符号“ Hello”。 Please help. 请帮忙。 Thanks 谢谢
You need to call it in onCreate method. 您需要在onCreate方法中调用它。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetIP setip = new SetIP();
setip.hello();
}
You shouldn't call a method of an object of any of the classes on the fly as you are calling now, As you told your // OnCreate and Stuff
is below than your object's method call. 您不应像现在所调用的那样即时调用任何类的对象的方法,正如您所告诉的那样, // OnCreate and Stuff
低于对象的方法调用。
It has to be inside constructor or some methods, Like here 它必须在构造函数或某些方法中,例如这里
SetIP setip = new SetIP();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setip.hello();
}
OR 要么
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SetIP setip = new SetIP();
setip.hello();
}
You can instantiate SetIP as global variable to MainActivity, but calling the function should still resides within a function of MainActivity. 您可以将SetIP实例化为MainActivity的全局变量,但调用该函数仍应驻留在MainActivity的函数内。 One example is to put this in onCreate activity as below 一个示例是将其放在如下所示的onCreate活动中
public class MainActivity extends AppCompatActivity {
SetIP setip = new SetIP();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setip.hello();
}
// Other Stuff
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetIP setip = new SetIP();
setip.hello();
}
// Other methods
}
You need change only method is static like 您只需要更改方法是静态的
public class SetIP {
public static void hello(){
Log.d("System", "Hello World!");
}
}
Try this work. 试试这个工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.