【问题标题】:Handling setDisplayHomeAsUpEnabled with fragments使用片段处理 setDisplayHomeAsUpEnabled
【发布时间】:2012-04-22 02:56:28
【问题描述】:

我有一个基于片段的布局,其中包含两个 ListFragment(A 和 B),都包含在一个活动中(称为 ListingActivity 1)。当应用启动时,ListingActivity 1 被调用,根据设备是纵向还是横向,要么只显示 ListFragment A,要么同时显示 ListFragment。

当你点击 Fragment A 的 ListView 中的一个项目时,会显示 Fragment B 的 ListView。当您单击 Fragment B 的 ListView 中的一个项目时,它会转到一个新活动(活动 1)。

我正在使用此代码(称为 ListingActivity 2)来确定是单独显示 ListFragment B 还是与 ListFragment A 一起显示:

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);
    }
}

【问题讨论】:

    标签: android android-intent android-fragments android-actionbar


    【解决方案1】:

    老实说,我认为您的解决方案是实现所描述行为的正确方法。它遵守所有关于向上导航的 Android 标准(在这种情况下,它应该像“后退”按钮一样,我相信)。我唯一要重新考虑的是您对Intent.FLAG_ACTIVITY_NEW_TASK 标志的使用。来自 Android 文档:

    任务是用户为实现目标而遵循的一系列活动。

    在这种情况下,您似乎没有开始一项新任务。

    【讨论】:

    • 听起来不错。我想如果我正在检查 ListActivity 中的方向是否为横向,我应该能够使用“向上”按钮。理想情况下,我想检查smallestScreenWidthDp,但这并没有引入Android 3.2。至于使用Intent.FLAG_ACTIVITY_NEW_TASK,我在上面的代码中使用addFlags 方法,不确定是否应该在其他地方使用它。
    • @Alex 使用向上导航它转到所需的片段,但它再次重新加载以显示。如何避免这种情况?我正在实施这个解决方案stackoverflow.com/questions/24596036/…,但它会重新加载该片段。原因很明显,它正在加载活动。但是如何避免呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2016-07-02
    • 2013-03-10
    • 2014-04-28
    • 1970-01-01
    相关资源
    最近更新 更多