在activity_main之外的其他活动中添加操作栏

时间:2016-01-30 10:20:43

标签: android android-activity android-actionbar android-actionbaractivity

我正在开发一个简单的应用程序,它有一些活动。因此,当我启动应用程序并进入我的MainActivity时,我有我的操作栏,一切都很棒。 MainActivity中有2个按钮,点击它们可以带您进入其他活动。我想要做的是我想对这些次要活动实施一个操作栏。我已经尝试了在谷歌或youtube上找到的所有东西,但没有任何效果。希望你们能帮助我。我希望将操作栏放在BACK按钮上,它会将我带回activity_main,但我当然需要一个操作栏。我将为您提供我的一个辅助活动的代码,以便您可以建议我添加什么。

牛顿活动

public class NewtonScreen extends Activity
{
     private Button theAnswerButton, theHintButton, theSuckButton;

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

     setContentView(R.layout.newton_layout);

     theAnswerButton = (Button) findViewById(R.id.answer_button);
     theHintButton = (Button) findViewById(R.id.hint_button);
     theSuckButton = (Button)findViewById(R.id.suck_at_physics_button);


}

/**@Override
     public boolean onCreateOptionsMenu(Menu menu) {
     //Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.newton_menu, menu);
          return true;
}

@Override
  public boolean onOptionsItemSelected(MenuItem item) {
     // Handle action bar item clicks here. The action bar will
     // automatically handle clicks on the Home/Up button, so long
     // as you specify a parent activity in AndroidManifest.xml.
     int id = item.getItemId();

     //noinspection SimplifiableIfStatement
     if (id == R.id.action_settings) {
         return true;
    }

      return super.onOptionsItemSelected(item);
}**/

// Some other methods that are not important for this issue

正如你所看到的,我试图放置这两个Override方法,我甚至创建了一个newton_menu布局,但似乎它不起作用。

牛顿菜单

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".NewtonScreen">

<item 
    android:id="@+id/newton_action_exit"
    android:title="@string/action_exit"
    android:orderInCategory="101"
    app:showAsAction="ifRoom"
    />

3 个答案:

答案 0 :(得分:1)

扩展活动更改为扩展AppCompatActivity

在oncreate中调用此代码

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

和此代码

    @Override
public boolean onOptionsItemSelected(int featureId, MenuItem item) {
     int itemId = item.getItemId();
     if(itemId == android.R.id.home){
         finish();
     }
     return true;
}

答案 1 :(得分:1)

  

我认为您的项目或您的第二个类不支持actionbar。您应该在style.xml文件中更改它并确保第二个类应用它。    示例style.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

答案 2 :(得分:0)

只需使用Mainactivity扩展您的所有活动(可以将其视为具有操作栏的基本活动)。

例如:让您的MainActivity扩展AppCompatActivity

让其他活动扩展为MainActivity,如

SecondActivity扩展了MainActivity。

希望这能解决您的问题。