我正在尝试更改操作栏中的图标,但无法使其正常工作。如果我将getIcon()。toString()发送到日志,似乎图标已被修改,但操作栏未更新。
这是主要的活动布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="81dp">
<android.support.v7.widget.Toolbar
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:minHeight="?attr/actionBarSize"
android:theme="@style/AppTheme.AppBarOverlay"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:popupTheme="@style/AppTheme">
</android.support.v7.widget.Toolbar>
菜单xml文件:
<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=".MainActivity">
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
android:orderInCategory="100"
app:showAsAction="never" />
<item
android:id="@+id/about"
android:title="@string/about"
android:orderInCategory="110"
app:showAsAction="never" />
<item
android:id="@+id/connect"
android:title="Connect"
android:icon="@drawable/ic_play"
android:orderInCategory="130"
app:showAsAction="always" />
<item
android:id="@+id/testin"
android:title="Test_in"
android:icon="@drawable/ic_testin"
android:orderInCategory="120"
app:showAsAction="always" />
主要活动代码:
//Menu Items
MenuItem testinMenu, connectMenu;
Menu actionMenu;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Action Bar
toolbar = findViewById( R.id.appbar);
setSupportActionBar( toolbar);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menumain, menu);
actionMenu = menu;
connectMenu = (MenuItem) menu.findItem(R.id.connect);
testinMenu = (MenuItem) menu.findItem(R.id.testin);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.connect: {
connectMenu.setIcon( R.drawable.ic_stop);
invalidateOptionsMenu();
if( isRainbowConnected == false) {
connect();
} else
disconnect();
break;
}
case R.id.testin: {
if( isRainbowConnected == true)
sendTestIn();
break;
}
// case blocks for other MenuItems (if any)
}
return true;
}
我已经尝试了一切,但似乎没有任何效果。 预先感谢!