【问题标题】:Assigning Values to a TextView from a different class将值分配给来自不同类的 TextView
【发布时间】:2012-07-07 08:21:27
【问题描述】:
TestaActivity.java
public class TestaActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvText=(TextView)findViewById(R.id.textView1);
tvText.setText("Sample");
}
}
打印.java
public class Print {
public Print(Context tempContext) {
//I want to assign the value to the tvText from here
}
}
在上面的示例中,您可以看到我已将 tvText 中的文本设置为“Sample”。同样,一旦创建,我需要在 Print 类中为 textView1 ID 分配一些值。
请帮我找出方法。
【问题讨论】:
标签:
android
class
android-layout
android-context
settext
【解决方案1】:
如果您的类 Print 在 TestaActivity 出现在屏幕上时被实例化,那么您可以获得 tvText 引用,以某种方式将 TestaActivity 引用传递给 Print。
也许你可以通过构造函数传递它:
从 TestaActivity 你做:
Print print = new Print(this);
其中 this 代表 TestaActivity 的实例。
然后在您的 Print 代码中您可以执行以下操作:
TextView tvText = (TextView)((TestaActivity)context.findViewById(R.id.textView1));
tvText.setText("Sample");
另一个解决方案是提供一个来自 TestaActivity 的接口,对外部透明,它管理你在 textview(或其他)上的更改。
类似的东西:
private TextView tvText;
public void setTvText(String str){
tvText.setText( str );
}
然后在您的 Print 类中:
((TestaActivity)context).setTvText( "Sample" );
【解决方案2】:
尝试:
public class Print {
protected TestaActivity context;
public Print(Context tempContext) {
context = tempContext;
}
public void changetextViewtext(final String msg){
context.runOnUiThread(new Runnable() {
@Override
public void run() {
//assign the value to the tvText from here
context.tvText.setText("Hello Test");
}
});
}
}
并从 Activity 调用 changetextViewtext 以从 Print 类更改 TextView 文本
public class TestaActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvText=(TextView)findViewById(R.id.textView1);
tvText.setText("Sample");
Print myPrint = new Print(this);
myPrint.changetextViewtext("Hello World !!!");
}
}
根据您的需要!!!!:)
【解决方案3】:
@imran - 解决方案是正确的,只是您希望在构造函数或方法中将 TextView 作为参数传递。
在方法中对 TextView 进行编码是不好的,因为您不能重复使用它。