Set toolbar title
Asked Answered
B

7

17

I am trying to set my toolbar title like so:

public class StatisticsPage extends Fragment  {

    public StatisticsPage(){}
    private FragmentTabHost mTabHost;

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

        View rootView = inflater.inflate(R.layout.statistics_pagelayout, container, false);

        Spinner spinner = (Spinner) rootView.findViewById(R.id.statsSpin);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.statspage, R.layout.dropdown_item);
        spinner.setAdapter(adapter);
        getSupportActionBar().setTitle("My title");

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {

                switch (position) {
                    case 0:
                        break;
                    case 1:
                        // do whatever stuff you wanna do here
                        Fragment Fragment_one;
                        FragmentManager man= getActivity().getSupportFragmentManager();
                        FragmentTransaction tran = man.beginTransaction();
                        Fragment_one = new BreweryStatistics();
                        tran.replace(R.id.main, Fragment_one);//tran.
                        tran.addToBackStack(null);
                        tran.commit();
                        break;
                    case 2:
                        Fragment Fragment_two;
                        FragmentManager mantwo= getActivity().getSupportFragmentManager();
                        FragmentTransaction trantwo = mantwo.beginTransaction();
                        Fragment_two = new StyleStatistics();
                        trantwo.replace(R.id.main, Fragment_two);//tran.
                        trantwo.addToBackStack(null);
                        trantwo.commit();
                        break;
                    case 3:
                        Fragment Fragment_three;
                        FragmentManager manthree= getActivity().getSupportFragmentManager();
                        FragmentTransaction tranthree = manthree.beginTransaction();
                        Fragment_three = new TasteStatisticsPage();
                        tranthree.replace(R.id.main, Fragment_three);//tran.
                        tranthree.addToBackStack(null);
                        tranthree.commit();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }
        });

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);
        String url = "myURL";
        String userURLComp = "u=" + userID;

        url = url + userURLComp ;

        new getBasicStats(getActivity()).execute(url);

        return rootView;
    }
}

Basically this line in the above code does not work in the fragment:

getSupportActionBar().setTitle("My title");

Also How can I stop my app title from showing up in the app bar? I would also like to make the title white when I can set it.

Belter answered 10/3, 2015 at 0:54 Comment(5)
Try adding getActivity() before the getSupportFragmentSuperposition
still says cannot resolve method getsuuportactionbarBelter
What about? ((ActionBarActivity)getActivity()).getSupportActionBar().setTitle("Home");Superposition
worked perfectly, can I theme it white some how?Belter
I would ask a separate question for that. I'm going to answer this question instead of commentsSuperposition
S
70

Change it to

((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Home");

You needed to tell the activity it is an AppCompatActivity.

Then you use getActivity() to get the main activity since you are in a fragment.

Then just set the title as usual.

Superposition answered 10/3, 2015 at 1:8 Comment(6)
if you happen to know how to change the color, i just posted that question tooBelter
While this answer is probably correct and useful, it is preferred if you include some explanation along with it to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked.Ickes
Sorry Kevin, I'll add more. Should've known.Superposition
is there a way to do this in an async task?Belter
The easiest and simplest answerClio
Thanks, very easiest wayBridgetbridgetown
B
11

In kotlin

(activity as? AppCompatActivity)?.supportActionBar?.title = "title"

Edit: Added null safe operator ? to avoid NullPointer in case ActionBar not available

Burghley answered 18/9, 2018 at 19:15 Comment(0)
G
3

Actually you can just do the following:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    getActivity().setTitle("My title");
}

I make the change in onActivityCreated because the Activity may have not been fully initialized yet in onCreateView. In onActivityCreated there is no risk of getting a NullPointerException.

NOTE: I am using an AppCompatActivity with a Toolbar and v4 Fragments associated to it.

Gena answered 19/4, 2016 at 7:55 Comment(2)
Where is onActivityCreated? In the main activity or the fragment? I have a list in my main activity and when I click on a list item a fragment is opened and the toolbar title should change. My click handler is in the fragment; does it need to be moved to the activity?Digged
@HEATH3N onActivityCreated is meant for the fragments, when onActivityCreated is called on the fragment, it means that its parent activity is fully initialized (no risk of null pointers).Gena
P
2

Kotlin set title from resources

Activity:

setTitle(R.string.some_title)

Fragment:

activity?.setTitle(R.string.some_title)
Presbyterial answered 1/10, 2018 at 10:46 Comment(0)
A
1

The best and easiest way to do this, is to go to Android Manifest and change the label within the Activity section. This is what's responsible for labelling the Activity along the toolbar. This saves you writing lines of code in the class file.

Anselmo answered 7/7, 2017 at 12:35 Comment(0)
B
0

In Kotlin:

in onCreate method put title = "Some Text Here"

Bledsoe answered 3/8, 2019 at 21:26 Comment(0)
P
-2

This worked for me inside an activity. I haven't tried it inside fragment.

this.setTitle("welcome")
ActiviryName.this.setTitle("welcome");
Polypoid answered 14/3, 2017 at 16:48 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. Also, you have a typo in Activity. BTW, how is this different from the other answers?Ferrocyanide

© 2022 - 2024 — McMap. All rights reserved.