【问题标题】:Android Change View After Certain Amount of TimeAndroid 在一定时间后更改视图
【发布时间】:2015-08-25 01:19:23
【问题描述】:

我是 AndroidStudio 的新手,我很难找到一种无需用户操作即可更改视图的方法。更具体地说,我试图让我的应用程序在打开时显示一个标题屏幕,然后在几秒钟后切换到主界面。我在 android 教程中找到了用于将视图从当前视图更改为 DisplayMessageActivity 类的代码:

Intent intent = new Intent(this, DisplayMessageActivity.class);
startActivity(intent);

我尝试在我的标题屏幕活动的 onCreate 方法中使用此代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.title_screen);
    try {
        Thread.sleep(5000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    startActivity(intent);
}

然后我在新的 Activity 中设置了第二个视图。我还尝试在 onCreate 方法中使用两个单独的视图:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.title_screen);
    try {
        Thread.sleep(5000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    setContentView(R.layout.main_menu);
}

但是,在这两种情况下,它只显示第二个视图。我哪里错了?

【问题讨论】:

    标签: java android android-studio oncreate


    【解决方案1】:

    你在两个活动中使用相同的布局,修复它(R.layout.....)

    避免使用 Thread.sleep,因为它会阻塞应用程序本身。 您必须在调用第二个活动时引入延迟。请参考 https://www.youtube.com/watch?v=LCLO7q2uhOs

    您的以下代码应该放在一个处理程序块中,并具有您想要的时间延迟

     Intent intent = new Intent(this, DisplayMessageActivity.class);
        startActivity(intent);
    

    【讨论】:

    • 看看这两个 onCreate 方法都来自同一个 Activity(但他做了两个选项来证明这一点)。
    【解决方案2】:

    这里:Intent intent = new Intent(this, DisplayMessageActivity.class);

    问题在于您在两种情况下都将Intent 发送到同一班级(DisplayMessageActivity.class)。您必须在 onCreate 方法中更改要发送 Intent 的类(第二个视图)。

    Intent intent = new Intent(this, **The class in which you are going to show your second view**);
    

    希望对你有用!

    【讨论】:

      猜你喜欢
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-06
      • 1970-01-01
      • 2018-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多