Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

android - Can't get Action Bar in fragment class

I have an activity with three fragment classes inside it. I get an error when trying to change the action bar title from inside of them. If I try to make the classes just public and not public static I get an error when I try to start that class. It should be pretty clear that the code is for preferences although that shouldn't change anything . Here's the code:

package com.simon.wikiics;

import android.preference.*;
import android.os.*;
import java.util.*;

public class MainSettingsActivity extends PreferenceActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public void onBuildHeaders(List<Header> target) {
    loadHeadersFromResource(R.xml.headers, target);
}

//If I don't make the classes static my app force closes when I try to start them
public static class NavigationSettingsActivity extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.navigation);
        //The getActionBar() is what is giving me the error
        getActionBar().setTitle("Navigation");

    }
}

public static class InterfaceSettingsActivity extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.interf);
        //The getActionBar() is what is giving me the error
        getActionBar().setTitle("Interface");
    }

}

public static class OtherSettingsActivity extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.other);
        //The getActionBar() is what is giving me the error
        getActionBar().setTitle("Other");
    }
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@Robert Estivil If you are using AppCompatActivity then use this:

actionBar = ((AppCompatActivity)getActivity()).getSupportActionBar();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...