2015-08-29 504 views
3

我知道這個問題已經發布了數百萬次,但我無法爲我的案例找到可行的解決方案。更改searchView的光標顏色

我需要改變我的searchView的光標顏色。 我沒有searchView的xml定義,我以編程方式使用它。

這裏我的代碼:

public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_contacts, menu); 

    SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
    SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView(); 
    search.setSearchableInfo(manager.getSearchableInfo(getComponentName())); 

    return true; 
} 

我使用這個: import android.support.v7.widget.SearchView;

感謝

+1

如果您正在使用最新的程序兼容性庫,我想你可以改變光標通過更改主題中的** colorAccent **值來實現顏色。 – DavidH

回答

31

你嘗試了嗎?

public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_contacts, menu); 

    SearchManager manager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); 
    SearchView search = (SearchView) menu.findItem(R.id.action_search).getActionView(); 
    search.setSearchableInfo(manager.getSearchableInfo(getComponentName())); 

    AutoCompleteTextView searchTextView = (AutoCompleteTextView) search.findViewById(android.support.v7.appcompat.R.id.search_src_text); 
    try { 
     Field mCursorDrawableRes = TextView.class.getDeclaredField("mCursorDrawableRes"); 
     mCursorDrawableRes.setAccessible(true); 
     mCursorDrawableRes.set(searchTextView, R.drawable.cursor); //This sets the cursor resource ID to 0 or @null which will make it visible on white background 
    } catch (Exception e) { 
    } 
    return super.onCreateOptionsMenu(menu); 
} 


繪製/ cursor.xml

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" > 
    <solid android:color="#ffffff" /> 
    <size android:width="2dp" /> 
</shape> 

例如:Changing the cursor color in SearchView without ActionBarSherlock

+0

這對我來說工作得很好。謝謝... –

+1

工作正常,但它並沒有刪除默認光標,因此都顯示在同一時間 –