1.创建一个 cm_layout_search_view.xml 用来布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="24dp" android:background="@drawable/cm_search_bg" android:gravity="center_vertical" android:orientation="horizontal"> <ImageView android:layout_width="18dp" android:layout_height="18dp" android:layout_gravity="center" android:layout_marginLeft="5dp" android:scaleType="fitCenter" android:src="@drawable/cloud_icon_search" /> <!--如果想换成可以输入的,直接把这里换成 EditTextView即可--> <TextView android:id="@+id/tv_title" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="5dp" /> </LinearLayout>
2. 创建 SearchView.java
import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; /** * <p> * Created by Xulin on 2017/11/14 * email: xulin67@163.com. * description: */ public class SearchView extends LinearLayout implements View.OnClickListener { private Context context; public SearchView(Context context) { super(context); this.context = context; initView(); } public SearchView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; initView(); } public SearchView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; initView(); } private void initView() { //加载布局文件 LayoutInflater.from(context).inflate(R.layout.cm_layout_search_view, this); setOnClickListener(this); } @Override public void onClick(View v) { } }
3.在其他布局引用
<com.cust.base.view.SearchView android:id="@+id/sch_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginLeft="@dimen/margin_18" android:layout_marginRight="@dimen/margin_18" />
4.最后看看效果吧
5.补充一个 样式 cm_search_bg.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"> <solid android:color="#eeeff3" /> <corners android:bottomLeftRadius="2dp" android:bottomRightRadius="2dp" android:topLeftRadius="2dp" android:topRightRadius="2dp" /> </shape>