我有一個活動:Activity1,應該打開一次(第一次啟動) Activity2,主屏幕。在第一次啟動時在Activity1中做了一些事情之后,每次啟動Activity2都應該打開。我有點想出了如何做到這一點,它工作得很好,但是當我按下手機上的“后退”按鈕時,Activity1突然出現。那么我該如何解決呢?我應該清除堆棧還是什么?這是我的代碼:活動 1:public class MainActivity extends AppCompatActivity { Button but1; EditText input1; TextView error1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome_page); if(getName("username")!=null){ Intent intent = new Intent(MainActivity.this, WelcomePageLast.class); startActivity(intent); } ListenerOnButton(); } public void ListenerOnButton(){ but1 = (Button)findViewById(R.id.welcome_page_button); input1 = (EditText)findViewById(R.id.username_input); error1 = (TextView)findViewById(R.id.name_error); but1.setOnClickListener( new View.OnClickListener() { public void onClick(View view){ if (input1.getText().toString().length() < 2){ error1.setText("Слишком короткое имя!"); }else { error1.setText(""); Intent intent = new Intent(MainActivity.this, WelcomePageLast.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_CLEAR_TOP); setName("username", input1.getText().toString()); startActivity(intent); } } } ); } public void setName(String key, String value){ SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString(key, value); editor.apply(); }
查看完整描述