標籤:android style blog class code java
首先,給Actionbar添加返回表徵圖:
代碼:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings); isSendMsg = (Switch) findViewById(R.id.isSendMessage); isCall = (Switch) findViewById(R.id.isCall); data = (initDataApp)getApplication(); isSendMsg.setChecked(data.isSendMsg()); isCall.setChecked(data.isCall()); ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); //actionBar.setListNavigationCallbacks(adapter, callback); }
設定可用
重寫onOptionsItemSelected方法:
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: //NavUtils.navigateUpFromSameTask(this);//onSaveInstanceState // This is called when the Home (Up) button is pressed // in the Action Bar. Intent parentActivityIntent = new Intent(this, MainActivity.class); parentActivityIntent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(parentActivityIntent); finish(); // onBackPressed(); return true; } return super.onOptionsItemSelected(item); }
這個方法可以實現在調用向上返回時的處理。
接收:android.R.id.home處理這個android.R.id.home有幾種方式,先對其進行對比:
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: NavUtils.navigateUpFromSameTask(this);//onSaveInstanceState return true; } return super.onOptionsItemSelected(item); }
測試回退的時候,到上一個Activity時出現遺失資料現象。(測試方式,在A中加一個EditText,然後輸入資料,點擊跳入Bactivity ,此時使用向上一級導航會出現遺失資料)
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent parentActivityIntent = new Intent(this, MainActivity.class); parentActivityIntent.addFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(parentActivityIntent); finish(); return true; } return super.onOptionsItemSelected(item); }
使用intent方式一樣,遺失資料。
後來我看了看源碼,發現點擊手機的回退鍵時,觸發onBackPressed();方法,這個方法是返回時間軸上的上一個Activity,可以儲存資料。
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); }
但是在測試的時候發現,這個方法只返還上一,而不是邏輯指定的,例:A->B->C,從C返回到A,如果使用onBackPressed(),則回到B,所以不對。到此我們只能使用NavUtils.navigateUpFromSameTask(this);//onSaveInstanceState,但是要即時儲存資料。
下一篇我們將對儲存資料進行處理,進行現場保護!