-1
ナビゲーションドロワー内の項目を押したとき。新しいフラグメントを作成します。アクションバーのタイトルが更新されます。しかし、前のフラグメントが表示されたら、戻るボタンを押すと、ActionBarのタイトルは変わりません。これはDrawerItemClickListenerのコードです。Android MainActivityがフラグメントを更新しない戻るボタンが押されたときのonResumeのアクションバータイトル
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
mProgressBar.setVisibility(View.VISIBLE);
selectItem(position);
}
}
private void selectItem(final int position) {
mPendingRunnable = new Runnable() {
@Override
public void run() {
FragmentManager fragmentManager = getSupportFragmentManager();
switch (position) {
case 0:
HomeFragment homeFragment = new HomeFragment();
fragmentManager.beginTransaction()
.replace(R.id.activity_home, homeFragment,"homeFragment")
.commit();
setTitle("Home");
break;
case 1:
ProductFragment productFragment = new ProductFragment();
fragmentManager.beginTransaction()
.replace(R.id.activity_home, productFragment,"productFragment")
.addToBackStack(null)
.commit();
setTitle("Products");
break;
case 2:
BillFragment billFragment = new BillFragment();
fragmentManager.beginTransaction()
.replace(R.id.activity_home, billFragment,"billFragment")
.addToBackStack(null)
.commit();
setTitle("Bill");
break;
}
mProgressBar.setVisibility(View.GONE);
}
};
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
アクティビティの状態が変更されたときに、タイトルを更新しようとしました。戻るボタンを押すと、actionbar TitleがdefaultTitleとして常に設定されます。その他の条件は実行されません。
代わりに、活動のonResume()
にタイトルを設定するのでは、フラグメントに
ActionBar
インスタンスを取得
@Override
protected void onResume() {
super.onResume();
HomeFragment homeFragment = (HomeFragment)getSupportFragmentManager().findFragmentByTag("homeFragment");
ProductFragment productFragment = (ProductFragment)getSupportFragmentManager().findFragmentByTag("productFragment");
BillFragment billFragment = (BillFragment)getSupportFragmentManager().findFragmentByTag("billFragment");
if(homeFragment != null && homeFragment.isVisible()) {
setTitle(getString(R.string.Home));
}
else if(productFragment != null && productFragment.isVisible())
{
setTitle(getString(R.string.Products));
}
else if(billFragment != null && billFragment.isVisible()){
setTitle(getString(R.string.Bills));
}
else {
setTitle("defaultTitle");
}
}
に以下のコードを設定すること働くしかし、その複雑な仕事。単一の場所ですべてのフラグメント名を更新する方法はありますか?なぜfindFragmentByTagとisVisibleが機能しないのですか? –
フラグメントを見つけて設定することは、上記のものより複雑で高価です。 – arjun