2017-01-09 66 views
1

在我的應用程序中,我有一個設置Activity來選擇應該僅在應用程序中第一次運行的語言,但它有時會在切換片段時顯示。我如何讓它只顯示第一次運行?應用程序運行時首次運行活動正在顯示

代碼:MainActivity

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

    }else{ 
    ... start the normal mainactivity 
    } 

的firstTime溫控功能:

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

     } 
    }); 
} 
+0

當你完成後,你應該完成活動。即在啓動新版本之後 –

+0

@TimCastelijns所以應該只添加finish();在啓動startActivity(mainIntent)之後的設置活動中;? – busted13

回答

0

你應該開始其他活動後寫finish();。不要忘記更改preferences.getBoolean("RanBefore1", false);並使其等於true。我假設你在選擇語言後希望它是真實的。 由於您未撥打finish();而啓動。

+0

我從設置的活動返回到mainacitivity之後添加了它,並且將RanBefore1更改爲false。 – busted13

相關問題