我的Android代码有问题。我想在android工具栏上创建按钮图标。并且图标在预览时显示。见下图 menu.xml
但是当我运行这个项目时,按钮图标没有显示出来。 run project
这是我的活动代码
public class Main2Activity extends AppCompatActivity {
private NavigationView navigationView;
private DrawerLayout dr;
private Toolbar toolbar;
private View navHeader;
private ActionBarDrawerToggle actionBarDrawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
dr = (DrawerLayout) findViewById(R.id.drawer);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setupDrawerContent(navigationView);
actionBarDrawerToggle = setupDrawerToggle();
dr.setDrawerListener(actionBarDrawerToggle);
selectDrawerItem(navigationView.getMenu().getItem(0));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
问题是什么?任何建议将不胜感激。谢谢
答案 0 :(得分:0)
在名为main_menu_tool.xml&的菜单中创建一个资源文件。粘贴波纹管代码
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:balloonberry="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/miCompose"
balloonberry:showAsAction="always"
android:icon="@drawable/menu"/>
<item
android:id="@+id/miProfile"
balloonberry:showAsAction="always"
android:icon="@drawable/week_view"/>
</menu>
在Main2Activity中,只需写一下......
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu_tool, menu);
return true;
}
答案 1 :(得分:0)
这是我为位置图标编写的Menu.XML的代码。 Image
<?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">
<item
android:id="@+id/Location1"
app:showAsAction="always"
android:icon="@drawable/location"
android:title="@string/location"
/>
</menu>
MainActivity.java的一部分代表图标
@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.Location1) {
Intent intent = new Intent(MainActivity.this,Location.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
希望它有所帮助。