【问题标题】:layout is not shown after waiting等待后不显示布局
【发布时间】:2014-06-08 17:43:31
【问题描述】:

我有三种布局:

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”,这将使布局显示。 但我找不到我的错误。

【问题讨论】:

  • 重新思考您的设计。为什么首先要为同一个活动多次设置内容视图?
  • 我不确定为什么这会失败,我很惊讶它没有抛出 NotResponding。如果您希望某些操作在三秒暂停后触发 UI 操作,请考虑使用 AsyncTask

标签: android layout


【解决方案1】:

没有显示您的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);

    }
}

【讨论】:

    【解决方案2】:

    试试这个,一定会成功的

        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();
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      相关资源
      最近更新 更多