我有擁有2個片段的MainActivity。第一個片段有導航抽屜,第二個片段沒有。在MainActivity中,我想重寫onBackPressed()方法,因此當導航抽屜被打開時,它必須關閉片段。但我不知道如何從Activity獲取片段的導航抽屜的狀態。下面的代碼:從活動中獲取片段的導航抽屜
MainActivity.java
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
FragmentListProduct.java
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.fragment_list_product_layout, container, false);
Toolbar toolbar = (Toolbar) mainView.findViewById(R.id.toolbar);
fragmentActivity.setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) mainView.findViewById(R.id.drawer_layout);
drawerToggle = new ActionBarDrawerToggle(fragmentActivity, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(drawerToggle);
drawerToggle.syncState();
navigationView = (NavigationView) mainView.findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.nav_cat_all);
}
當然,它給了我錯誤Cannot resolve symbol darwerlayout
。 之前,我做了drawerLayout
作爲靜態字段,但我得到了警告Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)
。那麼如何解決這個問題,或者你有另一種解決方案:d
我覺得你有這個完全錯誤的。爲什麼你想要在抽屜裏放一個抽屜?如果你想讓你的抽屜有一個片段,你應該把片段放在抽屜裏面,然後將抽屜佈局邏輯移動到MainActivity。但在你的情況下,你可以使用'findFragmentById'來查找片段並在片段中使用公共方法來執行此操作。 –
@NaveenDissanayake我不認爲這會出錯。其基於他的要求。和他展現自己的方式。對我來說,它的新的發酵曲線 –
你是什麼意思,「抽屜有一個片段?」,「抽屜裏面的片段」.. 我知道,抽屜包含菜單,而不是片段..對不起英語 – zihadrizkyef