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);
}
}
});
}
當你完成後,你應該完成活動。即在啓動新版本之後 –
@TimCastelijns所以應該只添加finish();在啓動startActivity(mainIntent)之後的設置活動中;? – busted13