安卓开发Android Studio新版本menu菜单不显示的问题
在新版本的Android Studio 直接配置菜单会显示不出来,新版本新建菜单经节如下:
activity_main.xml(布局文件):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?xml version= "1.0" encoding= "utf-8" ?> <RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http://schemas.android.com/tools" android:layout_width= "match_parent" android:layout_height= "match_parent" tools:context= ".MainActivity" > <androidx.appcompat.widget.Toolbar android:id= "@+id/toolbar" android:layout_width= "match_parent" android:layout_height= "?attr/actionBarSize" android:background= "?attr/colorPrimary" android:elevation= "4dp" android:theme= "@style/ThemeOverlay.AppCompat.ActionBar" android:popupTheme= "@style/ThemeOverlay.AppCompat.Light" > </androidx.appcompat.widget.Toolbar> <TextView android:id= "@+id/textView" android:layout_below= "@+id/toolbar" android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "Hello World!" /> </RelativeLayout> |
菜单文件,menu 文件配置如下,这一块几乎和低本一致,这块不重要
1 2 3 4 5 6 7 8 9 10 11 | <?xml version= "1.0" encoding= "utf-8" ?> <menu xmlns:android= "http://schemas.android.com/apk/res/android" > <item android:id= "@+id/menu_save" android:title= "Save" android:icon= "@drawable/ic_save" /> <item android:id= "@+id/menu_delete" android:title= "Delete" android:icon= "@drawable/ic_delete" /> </menu> |
最后就是主文件会多一句引用,MainActivity.java: 文件内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import androidx.appcompat.widget.Toolbar; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); textView = findViewById(R.id.textView); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true ; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.menu_save) { Toast.makeText( this , "Save clicked" , Toast.LENGTH_SHORT).show(); return true ; } else if (id == R.id.menu_delete) { Toast.makeText( this , "Delete clicked" , Toast.LENGTH_SHORT).show(); return true ; } return super.onOptionsItemSelected(item); } } |
如此配置以后运行效果如下:
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~