此代码在MainActivity的OnCreate中
inflater = getLayoutInflater();
serversView = inflater.inflate(R.layout.layout_home, null, false);
test = serversView.findViewById(R.id.titleDescription);
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
//some code
runOnUiThread(new Runnable() {
@Override
public void run() {
test.setText(utf8text+"mk");
Log.i(LOG_TAG,"serversView: "+ serversView + " test: "+ test + " test.getText().toString():"+ test.getText().toString());
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
必须使用Thread类!
当我登录Log.i(LOG_TAG," test.getText().toString():"+ test.getText().toString());
时,一切正常,文本已更改,但在UI中什么也没做。怎么了?
UPD: 当我这样做时:
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(utf8text);
Log.i(LOG_TAG,"textView.getText: "+ textView.getText().toString());
}
});
,如果textView在main_activity.xml中,则它会更改。但是,例如,如何使用LayoutInflater获取和更改另一个片段/活动中的TextView?
答案 0 :(得分:0)
在运行方法中添加以下行
serversView.invalidateViews();
例如
public void run() {
test.setText(utf8text+"mk");
serversView.invalidateViews();
Log.i(LOG_TAG,"serversView: "+ serversView + " test: "+ test + "test.getText().toString():"+ test.getText().toString());
}
答案 1 :(得分:0)
非UI线程无法更新UI,但是android提供了android.os.Handler类或AsyncTasks类,以下是线程处理程序尝试的示例代码。
public class MainActivity extends AppCompatActivity {
private ProgressBar progress;
private TextView text;
Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progress = findViewById(R.id.progressBar1);
text = findViewById(R.id.textView1);
handler = new Handler();
}
public void startProgress(View view) {
// do something long
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
doFakeWork();
handler.post(new Runnable(){
@Override
public void run() {
progress.setProgress(value);
if(value!=10)
text.setText("updated");
else
text.setText("updating");
}
});
}
}
};
new Thread(runnable).start(); }
// Simulating something timeconsuming
private void doFakeWork() {
try { SystemClock.sleep(5000);} catch (Exception e) {e.printStackTrace();}}}
希望它对您有帮助,祝您好运。
答案 2 :(得分:0)
线程处理程序类,尝试一下。
public class MainActivity extends AppCompatActivity {
TextView test;
Handler handle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test = findViewById(R.id.titleDescription);
handle = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
test.setText("Hey! Text Changed");
}
};
new Thread(runnable).start();
}
}