应用程序运行时显示首次运行的活动

时间:2017-01-09 14:44:44

标签: android

在我的应用程序中,我有一个设置Activity来选择应该仅在应用程序的第一次运行的语言,但是当我切换片段时它有时会显示。如何让它仅在第一次运行时显示?

代码:MainActivity

     if (isFirstTime()) {
        Intent myIntent;
        myIntent = new Intent(this, Settings.class);
        startActivity(myIntent);

    }else{
   ... start the normal mainactivity
  }

firstTime fucntion:

  private boolean isFirstTime() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean ranBefore = preferences.getBoolean("RanBefore1", false);
    return !ranBefore;
}

设置活动:

    private Spinner spinner;
private Button button;
private String lang="";

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


    setContentView(R.layout.settings_layout);
    findViewByID();
    setListeners();

}

private void findViewByID() {
    spinner = (Spinner) findViewById(R.id.spinner);
    button = (Button) findViewById(R.id.button2);
    ArrayAdapter adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.langs));



    spinner.setAdapter(adapter);

}

private void setListeners() {
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            switch (position) {
                case 0:
                    lang= "en";
                    break;
                case 1:
                    lang="fr";
                    break;
                case 2:
                    lang="ar";
                    break;
            }            }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("RanBefore1", true);
            editor.apply();
            if(getLanguage()!=null&&!getLanguage().contains(lang)) {
                setLanguage(lang);

                Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(mainIntent);
            }else {

                Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(mainIntent);
            }

        }
    });
}

1 个答案:

答案 0 :(得分:0)

在开始其他活动后,您应该写finish();。并且不要忘记更改preferences.getBoolean("RanBefore1", false);并使其等于true。我假设您在选择语言后希望它成为现实。 它开始是因为你没有调用finish();