我正在研究這個簡單的Android應用程序。我在Action Bar上有三個菜單項,每個菜單項在點擊它們時會膨脹3個不同的片段。在Android Studio中按下時更改操作欄菜單項圖標
我的問題:當我點擊其中一個菜單項目時,我想讓菜單項目的圖標變爲drawables文件夾中的另一個圖標,並保持這樣,直到我點擊另一個菜單項目,然後它將變爲第一個我點擊它之前的圖標。
我試圖使用一個選擇器.xml與「state_pressed」,當我點擊菜單項時,它會將圖標改變一秒,但是一旦我停止點擊,它就會回到第一個圖標。你可以在下面找到相關的代碼。如果你能幫助我解決這個問題,我會很感激。
submenu.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" >
<item
android:id="@+id/action_todo"
android:title=""
android:icon="@drawable/action_bar_selector"
app:showAsAction="always" />
</menu>
action_bar_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/ic_check_box_white_24dp"
android:state_pressed="true" />
<item
android:drawable="@drawable/ic_check_box_white_24dp_unpressed" />
</selector>
ProjectTodo.java(充氣操作欄在片段級) :
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
inflater.inflate(R.menu.submenu, menu);
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_back){
ProjectDetails frag = new ProjectDetails();
ProjectMainListFragmentChanger fragInterface = (ProjectMainListFragmentChanger) getActivity();
fragInterface.projectMainListChangeFragment(frag);
return false;
}
if(id == R.id.action_details){
return true;
}
if(id == R.id.action_todo){
ProjectDetails frag = new ProjectDetails();
ProjectTodoFragmentChanger fragInterface = (ProjectTodoFragmentChanger) getActivity();
fragInterface.projectTodoChangeFragment(frag);
return false;
}
return super.onOptionsItemSelected(item);
}
您可以看到當前應用程序的快速.gif圖像。當我點擊菜單項,它只會改變爲第二第二圖標,然後回到它原來的圖標:
每個活動都會創建一次操作欄。當需要更改操作欄中的某些內容時,您需要使操作欄無效。因此,無論何時單擊圖標,重新設置菜單項以及使操作欄無效 –