我写了一个函数来更改TextView
的文本。它位于包含TextView
的活动的类中。但是,当从另一个类调用它时,此函数不起作用。
该功能如下所示:
public class MainActivity extends AppCompatActivity {
public void changeTest() {
TextView test = (TextView) findViewById(R.id.textViewTest);
guessedLetters.setText("test");
}
}
如果我从我的MainActivity
调用此函数,它的效果非常好:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gameplay);
changeTest();
}
}
但如果我从扩展MainActivity的类中调用它,我会得到java.lang.NullPointerException at android.app.Activity.findViewById(Activity.java:1884)
。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gameplay);
MyClass myClass = new MyClass();
myClass.myFunction();
}
}
public class MyClass extends MainActivity {
public void myFunction() {
MainActivity mainActivity = new MainActivity();
mainActivity.changeTest();
}
}
我该如何解决这个问题?
答案 0 :(得分:1)
如果您希望此结果使用从MainActivity扩展的其他活动,则可以这样做:
<强> MainActivity 强>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//changeTest(this);
AnotherActivity a = new AnotherActivity();
a.updateTest(this);
}
public void changeTest(Activity activity) {
TextView test = (TextView)activity.findViewById(R.id.textViewTest);
test.setText("test");
}
}
<强> AnotherActivity 强>
public class AnotherActivity extends MainActivity {
public void updateTest(Activity activity){
changeTest(activity);
}
}
答案 1 :(得分:1)
这可以帮到你。
<强> MainActivity 强>
public class MainActivity extends AppCompatActivity {
public static TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textView);
OtherClass otherClass = new OtherClass();
otherClass.setText("TEST");
}
}
其他类
public class OtherClass {
public void setText(String txt){
MainActivity.tv.setText(txt);
}
}
答案 2 :(得分:1)
试试这个
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gameplay);
MyClass myClass = new MyClass();
myClass.myFunction(this);
}
}
public class MyClass extends MainActivity {
public void myFunction(MainActivity mainActivity) {
mainActivity.changeTest();
}
}