如何防止导航抽屉中的webview刷新

时间:2016-05-29 12:21:35

标签: android android-fragments webview

有一段时间我一直在使用viewpager在活动中显示webview个网页,但现在我已从viewpager更改为navigation drawer with RecyclerView,以显示webview },我的活动中有多个webview加载。

假设活动从 webview 1 开始,然后我点击 webview 2 如果我回到webview 1它将重新加载(刷新)并且我想要防止这种情况发生。

请帮忙。

这是我的主要活动。

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {
private Toolbar toolbar;
private FragmentDrawer drawerFragment;

private static String TAG = MainActivity.class.getSimpleName();

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    if (toolbar != null) {
        toolbar.setTitle(R.string.app_name);
        setSupportActionBar(toolbar);
    }
    drawerFragment = (FragmentDrawer)
            getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
    drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
    drawerFragment.setDrawerListener(this);


    displayView(0);

    }

@Override
public void onDrawerItemSelected(View view, int position) {
    displayView(position);
}

private void displayView(int position) {
    Fragment fragment = null;
    String title = getString(R.string.app_name);
    switch (position) {
        case 0:
            fragment = new TopRatedFragment();
            title = getString(R.string.title_home);
            break;
        case 1:
            fragment = new GamesFragment();
            title = getString(R.string.title_friends);
            break;
        case 2:
            fragment = new MoviesFragment();
            title = getString(R.string.title_messages);

        default:
            break;
    }

    if (fragment != null) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body, fragment);
        fragmentTransaction.commit();


        getSupportActionBar().setTitle(title);
    }
}
}

1 个答案:

答案 0 :(得分:0)

您是说要恢复相同的片段?这来自developer.android.com

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

这使后退导航按钮可以恢复已加载webview的相同片段。您每次都在switch语句中创建一个新的。

一旦你按下后退按钮的工作方式,就可以轻松地学习如何手动将特定片段从堆栈中拉出来。

编辑:

我不认为你正在刷新webview。每次通过调用空构造函数选择项时,都会创建一个新片段。您只需要创建一次每个片段,然后在返回到该webview时使用该片段的相同实例。使用后栈将使其在您离开应用程序时保持加载状态并稍后再返回。

还尝试使用静态方法YourFragment.newInstance(params),它返回YourFragment的新实例。这样做而不是空构造函数,因为这被认为是不正确的做法。