如何从另一个类更新活动的TextView
问题描述:
我是Android/Java编程的新手.我有两个类,一个是Activity
,另一个是普通的类.我的活动课包含一个TextView
.我可以从普通班级更新活动班级的TextView
吗?我尝试使用随机代码,但失败了.
I am new to Android/Java programming. I have two classes, one is an Activity
and the other is a normal class. My activity class contains a TextView
. Can I update the TextView
of the activity class from a normal class? I tried with random code, but it fails.
// activity class
public class MainMenu extends Activity {
public TextView txtView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView txtView = (TextView)findViewById(R.id.text);
}
}
// Other class
public class ClassB {
public ClassB() {
public void Update() {
TextView txtView = (TextView)findViewById(R.id.text);
txtView.setText("Hello");
}
}
}
答
您必须通过构造函数传递Context引用.
You have to pass the Context reference via constructor.
public class ClassB {
Context context;
public ClassB(Context context){
this.context=context;
}
public void Update(){
TextView txtView = (TextView) ((Activity)context).findViewById(R.id.text);
txtView.setText("Hello");
}