pdcc pdcc - 4 months ago 18
Android Question

change background of text field in searchview of android sdk

I am making an app and I have an activity with a searchview. My point is that I want to change the background color of the text field (the black rectangle in screnn shot).

My drawable:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:padding="10dp">

<solid android:color="#FFFFFF"/>

<corners
android:bottomRightRadius="10dp"
android:bottomLeftRadius="10dp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>
</shape>


My layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".SearchActivity" >

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="160sp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="@drawable/search_background"
android:orientation="vertical" >

<SearchView
android:id="@+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20sp"
android:layout_marginRight="20sp"
android:layout_marginTop="60sp"
android:actionViewClass="android.widget.SearchView"
android:background="@drawable/searchview"
android:iconifiedByDefault="false"
android:paddingLeft="10sp"
android:paddingTop="5sp"
android:scrollbarAlwaysDrawVerticalTrack="true"
android:showAsAction="collapseActionView"
android:focusable="false" >

</SearchView>

</LinearLayout>




Screenshot: http://imageshack.com/a/img829/3203/pd85.png

Can anybody help me with that?
thanks

Answer

After a little detective work you'll see that if you look at the source for the SearchView widget, you will see it basically extends LinearLayout with some added functionality. Looking at the line #242 it contains a widget (specifically a SearchAutoComplete which extends the AutoCompleteTextView which in the end extends EditText.

With that said, you'll need to modify the background attribute of that child element, with something on the lines of this:

SearchView c = findViewById(R.id.searchView); 
EditText e = (EditText)c.findViewById(c.getContext().getResources().getIdentifier("android:id/search_src_text", null, null));
         e.setBackgroundColor(Color.BLACK); //←If you just want a color
         e.setBackground(getResources().getDrawable(R.drawable.YOUR_DRAWABLE));
         //↑ If you want a drawable ↑ 

Usefull links: