2015-12-30 78 views
10

我有一個簡單的問題。在SearchView上更改工具欄顏色/樣式點擊

當點擊搜索圖標時,如何將工具欄的顏色/主題更改爲白色?

無論何時點擊搜索圖標,我都希望工具欄爲白色(後退箭頭爲黑色/灰色)。我已經在菜單項中添加

SearcView(android.support.v7.widget.SearchView)

enter image description here

enter image description here

然後回原來的顏色欄時後退按鈕被點擊。

+0

也許你可以添加一個監聽器'SearchView',當它擴大,改變'顏色Toolbar'。 – RockerFlower

+1

使用searchview單擊搜索圖標打開搜索活動與白色edittext希望您已閱讀此http://developer.android.com/guide/topics/search/search-dialog.html –

+0

我已經看到該鏈接,但它不相關到我所問的問題。 –

回答

12

enter image description here

Activity/Fragment代碼:

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.activity_menu, menu); 

    MenuItem searchMenuItem = menu.findItem(R.id.search); 
    if (searchMenuItem == null) { 
     return true; 
    } 

    searchView = (SearchView) searchMenuItem.getActionView(); 
    MenuItemCompat.setOnActionExpandListener(searchMenuItem, new MenuItemCompat.OnActionExpandListener() { 

     @Override 
     public boolean onMenuItemActionExpand(MenuItem item) { 
      // Set styles for expanded state here 
      if (getSupportActionBar() != null) { 
       getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED)); 
      } 
      return true; 
     } 

     @Override 
     public boolean onMenuItemActionCollapse(MenuItem item) { 
      // Set styles for collapsed state here 
      if (getSupportActionBar() != null) { 
       getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.BLUE)); 
      } 
      return true; 
     } 
    }); 

    return true; 
} 

而實際menu的XML是:

<?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/search" 
     android:title="@string/search_title" 
     android:icon="@drawable/ic_menu_search" 
     app:showAsAction="always|collapseActionView" 
     app:actionViewClass="android.support.v7.widget.SearchView" /> 
</menu> 

要更改的背面/ X-按鈕的顏色爲展開圖將此添加到您的款式中:

<item name="colorControlNormal">@color/my_great_color</item> 

爲了使顏色更平滑的變化 - 你可以製作動畫:Animate change of view background color on Android

我希望,它有助於

+0

謝謝!你提到的是部分工作。後退箭頭雖然存在但變得不可見,但後退箭頭和背景的顏色相同 –

+0

@FaizanMubasher添加了屏幕截圖 - 後退箭頭保持不變,這是絕對可見的。雖然,你可以隨時改變它的顏色以下這個技巧:http://stackoverflow.com/questions/26788464/how-to-change-color-of-the-back-arrow-in-the-new-material-theme(也在onMenuItemActionExpand和onMenuItemActionCollapse) –

+0

你是對的!其實我正在改變顏色從**藍**到**白**,這就是爲什麼後箭似乎是看不見的。而且,SearchView中的文字顏色也是白色的。無論如何,謝謝。 –