在尝试设置线程外部(在主线程上)的文本视图之前,您首先需要一个已设置的整数的全局变量。它需要预先设置,因为您启动的新线程将简单地启动并移动到下一行代码,因此 myInt 尚未设置。
然后,至少在最初使用主线程上的 textview 的预定全局整数值。如果您想从您启动的线程中更改它,则在您的类中创建一个方法,如 setIntValue(),它将从线程中传递整数并将全局变量设置为该值。如果您愿意,我可以稍后更新代码示例。
更新:示例代码
public class MainActivity extends Activity {
//your global int
int myInt
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
new Thread(new Runnable(){
public void run() {
int myRunnableInt = 1;
// Code below works fine and shows me myInt
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(String.valueOf(myRunnableInt));
//say you modified myRunnableInt and want the global int to reflect that...
setMyInt(myRunnableInt);
}
}).start();
//go ahead and initialize the global one here because you can't directly access your
myRunnableInt
myInt = 1;
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(String.valueOf(myInt)); //now you will have a value here to use
//method to set the global int value
private void setMyInt(int value){
myInt = value;
//you could also reset the textview here with the new value if you'd like
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(String.valueOf(myInt));
}
}
注意:如果您只希望能够重置 textview,而不是拥有一个全局的可操作变量,我建议将方法更改为只传入新整数并设置 textview,而不是存储全局变量,例如这:
private void setTextView(int newInt){
TextView textView = (TextView) findViewById(R.id.text_view);
textView.setText(String.valueOf(newInt));
}
如果您执行上述操作,请确保从线程内调用该方法时,在 UI 线程上调用它,如下所示: runOnUiThread(new Runnable()){ public void run(){ //update UI elements } }