【问题标题】:How to change the launcher activity based on an action [duplicate]如何根据操作更改启动器活动[重复]
【发布时间】:2018-10-19 06:23:30
【问题描述】:

我正在做一个类似于 uber 的应用程序,在注册活动中,我有一个复选框,用户可以在其中选择是想成为司机还是乘客。由于应用程序的风格,如果用户选择成为驱动程序,我需要将活动“drivermain”设置为应用程序的启动器。如果选择乘客,启动器活动将是“passengerMain”。一旦应用程序关闭并重新启动,它应该评估用户是司机还是乘客,以将其发送到正确的活动,因为应用程序关闭它会丢失复选框的状态。 我试图通过firebase比较数据,但我只是感到困惑和压力。

希望帮助 谢谢

【问题讨论】:

  • 创建一个启动器活动,如SplashActivity,然后根据您的逻辑将用户重定向到适当的活动

标签: java android database


【解决方案1】:

我认为你需要这样的东西:

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent;

    if (driver) {   // this is a boolean that you get from your Shared Preferences 
        intent = new Intent(MainActivity.this, DriverActivity.class);
    } else {
        intent = new Intent(MainActivity.this, PassengerActivity.class);
    }

    startActivity(intent);
    finish();
  }
}

您将使用上面的代码,在使用这种方法保存用户想要的应用类型之后:

https://developer.android.com/training/data-storage/shared-preferences

【讨论】:

  • 是的,有两件事要记住:不要调用 setContentView,因为它会增加应用程序启动时间的不必要开销。还要将 intent 变量标记为 final 以确保它被分配一次(以防您的应用程序启动变得更大)
  • 但是它只会根据复选框状态打开另一个活动,如果我再次启动应用程序,它将没有复选框的状态,因此它不会打开一个活动。我将编辑问题以明确
  • @JhoanNicolasAndresBecerraQ 在用户第一次打开应用程序并选择他想要的应用程序类型(司机或乘客)之后,您需要将此首选项保存在某处......关于如何的编辑答案保存他的选择
【解决方案2】:

您必须将用户选择存储在 sharedpreference 中,无论是司机还是乘客。

在您的 SplashActivity.class 中,从 sharedpreference 中获取用户选择并检查

如果驱动程序然后

启动drivermain.class

否则,

开始passengerMain.classs

【讨论】:

  • “sharedpreference”是否在应用关闭时保存数据?
  • @JhoanNicolasAndresBecerraQ 即使应用程序关闭,它也会保存数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多