不幸的是,没有办法设置 SearchView文本字段样式使用主题,样式和继承在 XML 作为您的 可以在 ActionBar 下拉列表中处理项目的背景。这是因为 R.stylable中的 selectableItemBackground被列为可设计风格,而 searchViewTextField(我们感兴趣的主题属性)不是。因此,我们不能轻松地从 XML 资源中访问它(您将得到一个 No resource found that matches the given name: attr 'android:searchViewTextField'错误)。
我们将使用上面创建的绘图工具为 LinearLayout视图设置背景,该视图在 SearchView中保存文本字段-其 id 为 android:id/search_plate。下面是在创建选项菜单时如何在代码中快速实现的方法:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
// Getting SearchView from XML layout by id defined there - my_search_view in this case
SearchView searchView = (SearchView) menu.findItem(R.id.my_search_view).getActionView();
// Getting id for 'search_plate' - the id is part of generate R file,
// so we have to get id on runtime.
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
// Getting the 'search_plate' LinearLayout.
View searchPlate = searchView.findViewById(searchPlateId);
// Setting background of 'search_plate' to earlier defined drawable.
searchPlate.setBackgroundResource(R.drawable.textfield_searchview_holo_light);
return super.onCreateOptionsMenu(menu);
}
}
最终效果
下面是最终结果的截图:
我怎么会变成这样
我认为值得一提的是我是如何做到这一点的,以便在定制其他视图时可以使用这种方法。
检查视图布局
I've checked how SearchView layout looks like. In SearchView 构造函数 one can find a line that inflates layout:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.custommenu, menu);
}
I've tired to do this as well and I'm using v7.
The application was crashed when I tried to grab the searchPlate via the getIdentifier() so I done it this way: