我有三个布局:
Layout1
-->onClick()-->show
Layout2
-->wait three seconds-->show
Layout3问题是没有显示Layout2。设置我使用的布局
setContentView(int);相关代码可能是:
public class TrainingActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
final Button inputButton = (Button)findViewById(R.id.inputButton);
inputButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
changeLayouts();
}
});
}
public void changeLayouts() {
setContentView(R.layout.layout2);
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
setContentView(R.layout.layout3);
}
}我的想法是Android可能使用类似"Event-Loop“的东西(如Qt),我的方法将阻塞控件以返回到"Event-Loop”,这将使布局显示。但是我找不到我的错误。
发布于 2013-06-19 01:17:21
您的layout2没有显示的问题是因为TimeUnit.MILLISECONDS.sleep(3000); -您在这里所做的是将您的UI线程置于睡眠状态,因此UI线程无法处理您更改布局的请求。当它被唤醒时-它会立即设置layout3,这就是为什么layout2没有显示。
您可以考虑使用Handler.postDelayed(Runnable, long)来推迟执行
因此,这应该会像您预期的那样工作:
public class TrainingActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
final Button inputButton = (Button)findViewById(R.id.inputButton);
inputButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
changeLayouts();
}
});
}
public void changeLayouts() {
setContentView(R.layout.layout2);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
setContentView(R.layout.layout3);
}
}, 3000);
}
}发布于 2013-09-17 17:39:40
试试这个,一定行得通。
public void changeLayouts() {
setContentView(R.layout.layout2);
Thread Timer = new Thread(){
public void run(){
try{
sleep(3000);
} catch(InterruptedException e){
e.printStackTrace();
} finally {
setContentView(R.layout.layout3);
}
}
}; Timer.start();
} https://stackoverflow.com/questions/17174676
复制相似问题