【问题标题】:How to add ActionBar to Activity in Android如何在Android中将ActionBar添加到Activity
【发布时间】:2016-03-18 05:52:09
【问题描述】:

我正在尝试将 ActionBar 添加到我的 android 活动中,但由于某些代码错误,应用程序会自动关闭。那么在 Activity 中显示 ActionBar 的正确代码是什么?

我在 onCreate 方法中尝试了这段代码,但它不起作用

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

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

【问题讨论】:

  • 请发布详细的错误信息。
  • 欢迎来到 StackOverflow!请参阅:How to create a Minimal, Complete, and Verifiable example,并尝试按照这些指南添加更多信息,以吸引更多对您的问题的积极关注。
  • 它在 actionBar.show() 上显示错误; @JohnnyShieh
  • 它在 actionBar.show() 上显示错误; @MeetTitan
  • getActionBar() => getSupportActionBar 并使用 Theme has ActionBar

标签: android android-activity android-actionbar


【解决方案1】:

试试这个,

  • 不要使用ActionBar 使用Toolbar
  • 将您的课程范围设为AppCompatActivity 而不是ActionBarActivity
  • 使用getSupportActionBar() 而不是getActionBar()
  • 默认显示Toolbar,因此您无需调用show() 方法。

Android Toolbar Example

【讨论】:

    【解决方案2】:

    以下代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-01
      • 1970-01-01
      • 2013-06-29
      • 2019-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多