我在我的菜单中使用原生Android抽屉,在MainActivity中:
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
//Home
fragment = new EntryFragment();
break;
case 1:
//Journal
fragment = new JournalFragment();
break;
case 2:
// Medications
fragment = new RxFragment();
break;
case 3:
// Reminders
fragment = new ReminderFragment();
break;
case 4:
// Counselor Locator
fragment = new LocatorFragment();
break;
case 5:
// Library
fragment = new LibraryFragment();
break;
case 6:
// Settings
break;
case 7:
// About
break;
default:
break;
}
if (fragment != null) {
fm.beginTransaction()
.replace(R.id.container, fragment).addToBackStack(String.valueOf(position)).commit();
String fragmentTitles[] = getResources().getStringArray(R.array.menu_array);
if(mActionBar != null) {
mActionBar.setTitle(fragmentTitles[position]);
}
} else {
Log.e("MainActivity", "Error in creating fragment");
}
但是我正在为另一个活动(EntryDetailActivity)重新调整EntryFragment,所以在EntryFragment中我定义了几种方法来根据托管它的活动来修改视图:
// Runs on the home page, shows/hides appropriate views
public void prepareForHomeView() {
mTxtDate.setVisibility(View.GONE);
mBtnDiffDay.setVisibility(View.GONE);
mEdtNotes.setVisibility(View.GONE);
mBtnSave.setVisibility(View.GONE);
mBtnDelete.setVisibility(View.GONE);
}
// Runs on the detail page, shows/hides appropriate views
public void prepareForDetailView() {
mBtnLog.setVisibility(View.GONE);
}
在EntryDetailActivity中,我可以轻松地在onResumeFragments()中调用prepareForDetailView(),但是我在MainActivity中调用prepareForHome()的问题,因为我根据菜单交换片段。有什么建议?
/ **更新** / 我通过addToBackstack()为片段分配了一个标签,该标签是菜单的位置。我还在MainActivity中添加了以下方法:
@Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
FragmentManager fm = getSupportFragmentManager();
EntryFragment entryFrag = (EntryFragment)fm.findFragmentByTag("0");
if(entryFrag != null) {
Log.v("rx", "Home frag is not null");
} else {
Log.v("rx", "Home frag is null");
}
}
答案 0 :(得分:1)
Activity
(或FragmentActivity
)有onAttachFragment(Fragment fragment)
- 您可以在instanceof
上执行fragment
以确定它是否是正确类型的片段(或使用id,tag等)并调用适当的方法。
或者,您可以让片段检查getActivity()
(onCreateView
/ onViewCreated
)。