您的位置:首页 > 移动开发 > Android开发

Android 开发之自定义 SearchView

2016-07-30 07:36 489 查看

Android 开发之自定义 SearchView

概述

官方的 SearchView 不好用,除了自己组装一个搜索框之外,完全可以在官方基础上改,以保证能满足大多数需求。

详情见代码和注释

public class MySearchView extends SearchView {

public MySearchView(Context context) {
super(context);
styleSearchView();
}

public MySearchView(Context context, AttributeSet attrs) {
super(context, attrs);
styleSearchView();
}

public void styleSearchView() {
//设置背景
this.setBackgroundResource(R.drawable.search_bg);
//提示文本内容
this.setQueryHint("请搜索");
//默认展开
this.setIconifiedByDefault(false);
//去除下划线
int plateId = this.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
LinearLayout plate = (LinearLayout)this.findViewById(plateId);
plate.setBackgroundColor(Color.TRANSPARENT);
//设置搜索框EditText
int searchPlateId = this.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
EditText searchPlate = (EditText)this.findViewById(searchPlateId);
//提示文本颜色
searchPlate.setHintTextColor(getResources().getColor(R.color.white));
searchPlate.setTextColor(Color.WHITE);
searchPlate.setBackgroundColor(Color.TRANSPARENT);
searchPlate.setGravity(Gravity.CENTER);
//设置光标样式
try {
Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
f.setAccessible(true);
f.set(searchPlate, R.drawable.cursor);
} catch (Exception e) {
e.printStackTrace();
}
//自定义搜索图标
int search_mag_icon_id = this.getContext().getResources().getIdentifier("android:id/search_mag_icon", null, null);
ImageView search_mag_icon = (ImageView) this.findViewById(search_mag_icon_id);
search_mag_icon.setImageResource(R.drawable.widget_search_icon);
search_mag_icon.setScaleType(ImageView.ScaleType.CENTER);
//自定义清除图标
int search_close_icon_id = this.getContext().getResources().getIdentifier("android:id/search_close_btn", null, null);
ImageView search_close_btn = (ImageView) this.findViewById(search_close_icon_id);
search_close_btn.setImageResource(R.drawable.widget_search_del);
}
}


总结:

完全自定义 searchview 就是这么简单
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  自定义 searchview