Adding ActionBar in Android Activity

2019-09-21 20:19发布

问题:

I am trying to add ActionBar to my android activity, but app automatically closes due to some code error. So what is the proper code to display ActionBar in the Activity?

I tried this code in onCreate method but its not working

ActionBar actionBar;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.timetable);

   actionBar = getActionBar();
   actionBar.setTitle("MY TITLE");
   actionBar.show();
 }

回答1:

Try this,

  • Don't use the ActionBar use Toolbar.
  • Make your class extent AppCompatActivity instead of ActionBarActivity.
  • Use getSupportActionBar() instead of getActionBar().
  • A Toolbar is shown by default, so you dont nedd to call the show() method.

Android Toolbar Example



回答2:

Following code:

public class Test extends Activity 
         {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        context = this.getApplicationContext();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        ActionBar actionBar = getActionBar();

        // show the action bar title
        actionBar.setDisplayShowTitleEnabled(true);
        // adding style and colour to title 
        SpannableString s = new SpannableString("Field");
        s.setSpan(new ForegroundColorSpan(Color.parseColor("#ffffff")), 0, s.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        actionBar.setTitle(s);

    }