我有一个基于片段的布局与两个ListFragments(A和B),都包含在一个活动(称为ListingActivity 1)。当应用程序启动时,将调用ListingActivity 1,并根据设备是纵向还是横向来显示ListFragment A或仅显示两个ListFragment。处理setDisplayHomeAsUpEnabled与片段
当您单击片段A的ListView中的项目时,将显示片段B的ListView。当你点击Fragment B的ListView中的一个项目时,它会转到一个新的活动(活动1)。
我使用这个代码(称为ListingActivity 2),以确定是否在它自己的显示ListFragment B或连同ListFragment答:
public class ListingActivity extends SherlockFragmentActivity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
final ListingFragment details = new ListingFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
}
在活动1,我使用setDisplayHomeAsUpEnabled
,以使Actionbar徽标作为后退按钮,但我不知道如何处理家庭意图。当设备处于肖像模式时,用户应该返回到ListingActivity 2,但是如果它们处于横向模式,他们应该返回到ListingActivity 1。
我打算做这样的事情,但它似乎真的hacky:
@Override
public boolean onOptionsItemSelected(final MenuItem item)
{
if (item.getItemId() == android.R.id.home)
{
final Intent intent;
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
intent = new Intent(this, ListingActivity1.class);
else
intent = new Intent(this, ListingActivity2.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
听起来不错。我猜如果我检查ListActivity中的方向是否处于横向,我应该可以选择“向上”按钮。理想情况下,我想检查'smallestScreenWidthDp',但这并未引入Android 3.2。至于使用'Intent.FLAG_ACTIVITY_NEW_TASK',我用'addFlags'方法在上面的代码中使用它,不确定是否应该在其他地方使用它。 – 2012-04-22 13:36:16
@Alex使用向上导航它会转到所需的片段,但它会重新加载以显示。如何避免这种情况?我正在实施这个解决方案http://stackoverflow.com/questions/24596036/actionbar-up-button-go-to-previous-activity-with-prev-fragment,但它重新加载该片段。原因很明显,它是加载活动。但如何避免这种情况? – Roon13 2015-06-19 07:09:54