Android Fragment Change Title

时间:2015-01-13 09:25:16

标签: android android-fragments

我的片段有问题。基本上,我有一个应用程序,它有一个导航抽屉和活动上的4个按钮。按下每个按钮时,它将显示另一个片段。我遇到的问题是我想在ActionBar上显示正确的标题。我可以在ActionBar的导航中显示所选项目。但当我按下按钮转到另一个片段时,我无法在ActionBar上显示标题。有什么想法吗?

这是我的示例代码: 的 HomeActivity.class

 private void displayView(final int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    switch (position) {
        case 0:
            fragment = new HomeFragment();
            break;
        case 1:
            fragment = new MyProfileFragment();
            break;
        case 2:
            fragment = new AboutFragment();
            break;
        default:
            break;
    }

    if (fragment != null) {
        fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame_container, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        setTitle(navMenuTitles[position]);
        drawer.closeDrawer(mDrawerList);
    } else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }

}

HomeFragment:

public class HomeFragment extends Fragment {

public HomeFragment() {
}

CardView card_cart, card_scan, card_categories, card_about;
Intent i;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    initControls(rootView);
    return rootView;
}

private void initControls(View rootView) {

    card_cart = (CardView) rootView.findViewById(R.id.card_cart);
    card_scan = (CardView) rootView.findViewById(R.id.card_scan);
    card_categories = (CardView) rootView.findViewById(R.id.card_categories);
    card_about = (CardView) rootView.findViewById(R.id.card_about);

    card_categories.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            i = new Intent(getActivity(), CategoriesActivity.class);
            startActivity(i);
        }
    });

    card_cart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MyCartFragment nextFrag = new MyCartFragment();
            getFragmentManager().beginTransaction()
                    .replace(R.id.frame_container, nextFrag)
                    .addToBackStack(null)
                    .commit();
        }
    });

    card_about.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AboutGrabHutFragment aboutFrag = new AboutGrabHutFragment();
            getFragmentManager().beginTransaction()
                    .setBreadCrumbTitle(getResources().getString(R.string.about))
                    .replace(R.id.frame_container, aboutFrag)
                    .addToBackStack(null)
                    .commit();


        }
    });

    card_scan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            i = new Intent(getActivity(), ScanActivity.class);
            startActivity(i);
        }
    });

}

在HomeFragment中,将找到这4个按钮。单击按钮,将转到另一个片段。我可以用这个显示:

card_about.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AboutGrabHutFragment aboutFrag = new AboutGrabHutFragment();
            getFragmentManager().beginTransaction()
                    .setBreadCrumbTitle(getResources().getString(R.string.about))
                    .replace(R.id.frame_container, aboutFrag)
                    .addToBackStack(null)
                    .commit();
            getActivity().setTitle("About");

        }
    });

但问题是,当我回去时,标题仍然是关于。希望有人知道如何解决这个问题。感谢。

3 个答案:

答案 0 :(得分:16)

在所需片段的onCreateView()方法上,调用Main Activity的setTitle("")方法。这样您就不需要检查背压事件。

这对我有用

例如***

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.id.your_fragment_layout, container,
                false);
        getActivity().setTitle("Your actionbar title");

        return rootView;
    }

<强>更新

您可以通过覆盖onResume方法来更改标题。为安全起见,您还可以覆盖setUserVisibleHint并在片段isVisibleToUser时更改标题。

答案 1 :(得分:1)

我在MainActivity中使用了onBackStackChangedListener,并在您在应用程序中导航时使用它来更新各种内容。您已经手动更改了标题,请尝试以下操作:

//manager is my FragmentManager
manager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            //I'm using this check to check if i'm on my MainFragment, you can use this in al kinds of ways. Decide yourself if you use it or not.
            if (manager.getBackStackEntryCount() == 1) {
                Class<? extends Fragment> FragClass;
                //mCurrentFragment is my global Fragment variable to do and check stuff with as below.
                FragClass = mCurrentFragment.getClass();
                if ((FragClass == DesiredFragment.class)) {
                    this.setTitle("desired title");
                } else if ((FragClass == OtherDesiredFragment.class)) {
                    //hope this helps.
                } //etc..
            }
        }
    });
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
    try {
        Class<? extends Fragment> FragClass;
        FragClass = mCurrentFragment.getClass();
        if ((FragClass == HomeFragment.class)) {
            System.exit(0);
        }
            popFragment();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

public void popFragment() {
    try {
        if (manager.getBackStackEntryCount() > 1) {
            manager.popBackStack();
            manager.executePendingTransactions();
            ArrayList<Fragment> reversedFragments = new ArrayList<Fragment>(manager.getFragments());
            Collections.reverse(reversedFragments);
            for (Fragment fragment : reversedFragments) {
                if (fragment != null) {
                    try {
                        mCurrentFragment = (BaseFragment) fragment;
                    } catch (ClassCastException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        } else {
            finish();
        }
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

答案 2 :(得分:1)

如果有人使用Kotlin而 @Sachin Rao 的答案不起作用(例如我的情况),那么我做了扩展功能来更改标题:

fun Fragment.setActivityTitle(@StringRes id: Int)
{
    (activity as AppCompatActivity?)!!.supportActionBar?.title = getString(id)
}

fun Fragment.setActivityTitle(title: String)
{
    (activity as AppCompatActivity?)!!.supportActionBar?.title = title
}

用法(在片段的任何位置):

setActivityTitle(R.string.title)
setActivityTitle("Title")