您的位置:首页 > 移动开发 > Android开发

Android 学习笔记之 Actionbar作为回到上一级

2014-05-11 10:04 211 查看
首先,给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,但是要实时保存数据。

下一篇我们将对保存数据进行处理,进行现场保护!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: