Android 超簡單的自定義SeachView

1.建立一個 cm_layout_search_view.xml 用來佈局java

<?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.javaandroid

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.在其餘佈局引用ide

<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.xmlthis

<?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>
相關文章
相關標籤/搜索