2016-01-07 108 views
0

我想更改搜索圖標因爲我的搜索按鈕圖標是白色的..Android:無法從searchView獲取搜索按鈕。

因此我找到了一個代碼來獲取搜索按鈕的視圖。

SearchView searchView = (SearchView) menu.findItem(R.id.action_search) 
       .getActionView(); 
     //SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE); 
     //searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); 

     int searchImgId = getResources().getIdentifier("android:id/search_button", null, null); 
     AppCompatImageView v = (AppCompatImageView) searchView.findViewById(searchImgId); 
     v.setImageResource(R.drawable.action_search); 

即使我將AppCompatImageView更改爲ImageView,但仍然爲null。我猜在searchView的搜索按鈕上的Id與searchImgId不匹配,所以我得到空。如何獲取正確的ID以檢索搜索按鈕。

+0

你誇大菜單XML文件中的onCreateOptionsMenu中,你必須搜索圖標? –

回答

0

我想你沒有充氣菜單的XML文件。你可以這樣做,這就是你變得空的原因。 你必須首先充氣你的菜單文件,從那裏你可以得到你的搜索按鈕ID。

@Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.sample_actions, menu); 
     SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search)); 

     searchView.setOnQueryTextListener(this); 
     searchView.onActionViewExpanded(); 
     return super.onCreateOptionsMenu(menu); 
    } 

sample_action.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/action_search" 
     android:title="@string/menu_search" 
     app:showAsAction="always" 
     app:actionViewClass="android.support.v7.widget.SearchView" 
     android:icon="@drawable/search_white"/> 
</menu> 
+0

但我和右側的搜索按鈕看到searchview是白色的顏色 – LittleFunny

+0

是否要更改搜索按鈕的顏色? –

+0

是的..但我通過的圖標是黑色的,它不知何故變成白色 – LittleFunny

0

更新

你可能會尋找這個

searchView.setBackgroundColor(Color.BLACK); 

但你想完全自定義它,你可以試試這個,我建議的代碼是,讓UI自己照顧自己。

我知道它是白色的,我知道這不是你想要的。您可以輕鬆地定製,以任何drawable,它也給你更大的自由發揮它

<LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="50dp" 
     android:layout_margin="8dp" 
     android:orientation="horizontal"> 

     <EditText 
      android:id="@+id/editText" 
      android:layout_width="match_parent" 
      android:layout_height="50dp" 
      android:layout_marginRight="-50dp" 
      android:layout_weight="1" 
      android:hint="some Text" 
      android:paddingLeft="4dp" /> 

     <ImageView 
      android:id="@+id/imageButton" 
      style="?actionBarStyle" 
      android:layout_width="50dp" 
      android:layout_height="50dp" 
      android:src="@android:drawable/ic_menu_search" /> 
    </LinearLayout> 

輸出

這種佈局會出現這樣的事情,從中可以改變搜索imageView沒有任何喧囂,根據需要改變editText的屬性。

所以你的View將在佈局中照顧,所以你只會在功能上編碼。更像Android方式

enter image description here