【发布时间】:2016-12-21 19:48:47
【问题描述】:
我已经为我的应用实现了一个Navigation Drawer,它在大多数情况下都能正常工作。
我的Home 选项卡执行了几个 API 请求以显示一些信息,这些请求和它们所需的工作量(即使它相当小)阻止了抽屉的中途关闭,使其不顺畅。
我的第一个“解决方案”是to load the fragment only after the Drawer closes,就像这样:
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
displaySelectedScreen(itemSelected.getItemId());
}
};
但这会在 Fragments 视图显示之前创建 0.5 秒的等待时间,从用户的角度来看,这并不是很有吸引力。
这是我activity_main.xml的一部分:
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
到目前为止,这就是我显示 Fragments 的方式:
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(final MenuItem item) {
displaySelectedScreen(item.getItemId());
drawer.closeDrawer(GravityCompat.START);
return true;
}
这是displaySelectedScreen 发生的事情:
private void displaySelectedScreen(int itemId) {
Fragment fragment;
fragment = checkFragment(itemId); // Instantiates the right Fragment
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// Close our Drawer since we have selected a valid item.
drawer.closeDrawer(GravityCompat.START);
}
您有什么建议可以让我的Navigation Drawer 顺利关闭?
编辑:
根据要求,这是我的 AsyncTask 的代码,它执行 API 请求并返回 JSONObject:
/**
* Requests information from the API via APIRequests
* Extends AsyncTask in order to do network-related actions in background.
*/
private class SearchInfo extends AsyncTask<Void, Integer, JSONObject> {
@Override
protected JSONObject doInBackground(Void... params) {
JSONObject information;
APIRequests apiRequests = new APIRequests();
information = apiRequests.getGameInfo();
requestDone = true;
return information;
}
}
APIRequest 的方法通过HttpURLConnection 执行一个简单的HTTP GET 并返回一个带有检索数据的JSONObject。
【问题讨论】:
-
displaySelectedScreen() 中发生了什么?
标签: android android-fragments navigation-drawer