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

Adding an action bar in other activities than activity_main

我正在开发一个简单的应用程序,其中包含一些活动。因此,当我启动应用程序并进入 MainActivity 时,我有了操作栏,一切都很好。 MainActivity 中有 2 个按钮,单击这些按钮可转到其他活动。我想做的是对那些次要活动实施操作栏。我已经尝试了在 google 或 youtube 上可以找到的所有内容,但没有任何效果。希望你们能帮助我。我希望在那个操作栏上放置 BACK 按钮,它将带我回到 activity_main 但当然我首先需要一个操作栏。我会给你我的一个次要活动的代码,这样你就可以建议我添加什么。

牛顿Activity

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

如您所见,我已尝试放置这 2 个覆盖方法,我什至创建了一个 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"
    />

扩展 Activity 更改为 扩展 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;
}

I think your project or your second class not support actionbar.You should change it in style.xml file and make sure second class apply it. Example style.xml

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

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

例如:让您的 MainActivity 扩展 AppCompatActivity

并让其他 Activity 使用 MainActivity 扩展,例如

SecondActivity 扩展了 MainActivity。

希望这能解决您的问题。