How to add ActionBar to Activity in Android

不羁岁月 提交于 2019-12-12 06:39:51

问题


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);

    }


来源:https://stackoverflow.com/questions/34238416/how-to-add-actionbar-to-activity-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!