編輯:關於 Android 程式設計
做專案時搜索框幾乎是標配,功能不難,但每次都要重寫一遍「監聽輸入 → 過濾資料 → 刷新 Adapter」的套路,實在有點膩。這次就把它封裝成一個可以直接丟進任何列表的通用元件。
先看成果:
視覺上沒什麼花俏,重點在於把「輸入框的變化」與「資料的過濾」這兩件重複的事收攏起來。
先想清楚一個搜索框由什麼組成:一個搜索圖示(通常是放大鏡)、一個輸入框、一個清除按鈕。行為上則是監聽輸入變化,據此控制清除按鈕的顯示與隱藏,並過濾資料、刷新列表。各家 App 的搜索框差異只在樣式,骨架幾乎一致。
於是設計方向定了:抽出一份通用版面,寫一個自定義 ViewGroup 處理顯示與事件,把「怎麼過濾」交給使用者決定的回呼。
先定義樣式屬性,方便各處客製。新增 attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="SearchBarIconMarginLeft" format="dimension" />
<attr name="SearchBarIconMarginRight" format="dimension" />
<attr name="SearchBarIconSrc" format="reference" />
<attr name="ClearIconMarginLeft" format="dimension" />
<attr name="ClearIconMarginRight" format="dimension" />
<attr name="ClearIconSrc" format="reference" />
<attr name="SearchTextSize" format="dimension" />
<attr name="SearchTextColor" format="color" />
<declare-styleable name="CommolySearchView">
<attr name="SearchBarIconMarginLeft" />
<attr name="SearchBarIconMarginRight" />
<attr name="SearchBarIconSrc" />
<attr name="ClearIconMarginLeft" />
<attr name="ClearIconMarginRight" />
<attr name="ClearIconSrc" />
<attr name="SearchTextSize" />
<attr name="SearchTextColor" />
</declare-styleable>
</resources>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="@+id/iv_search_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="8dp"
android:src="@mipmap/search_bar_icon" />
<EditText
android:id="@+id/et_search"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@null"
android:singleLine="true" />
<ImageView
android:id="@+id/iv_search_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="@mipmap/search_clear_icon"
android:visibility="gone" />
</LinearLayout>
清除按鈕預設隱藏,輸入框用 layout_weight="1" 吃掉剩餘寬度,這樣左右兩側圖示的邊距調整不會互相影響。
類別繼承 LinearLayout,並用泛型 <T> 讓它能適配任意資料型別——這是「通用」的關鍵。建構子中先讀取自定義屬性,再載入版面:
public class CommolySearchView<T> extends LinearLayout {
private Context mContext;
private EditText mEditText;
private ImageView mClearImg;
private ImageView mSearchBarImg;
private BaseAdapter mAdapter;
private List<T> mDatas = new ArrayList<>(); // 目前顯示中的資料
private List<T> mDupDatas = new ArrayList<>(); // 原始資料備份
private List<T> mFilterDatas = new ArrayList<>(); // 過濾結果
private List<T> mDupFilterDatas = new ArrayList<>(); // 過濾結果備份
private Bitmap mSearchIcon;
private int mSearchIconMarginLeft, mSearchIconMarginRight;
private Bitmap mClearIcon;
private int mClearIconMarginLeft, mClearIconMarginRight;
private int mSearchTextSize, mSearchTextColor;
public CommolySearchView(Context context) { this(context, null); }
public CommolySearchView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public CommolySearchView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CommolySearchView);
mSearchIcon = drawableToBitamp(ta.getDrawable(R.styleable.CommolySearchView_SearchBarIconSrc));
mSearchIconMarginLeft = px2dip(context, ta.getDimensionPixelOffset(
R.styleable.CommolySearchView_SearchBarIconMarginLeft, 0));
mSearchIconMarginRight = px2dip(context, ta.getDimensionPixelOffset(
R.styleable.CommolySearchView_SearchBarIconMarginRight, 0));
mClearIcon = drawableToBitamp(ta.getDrawable(R.styleable.CommolySearchView_ClearIconSrc));
mClearIconMarginLeft = px2dip(context, ta.getDimensionPixelOffset(
R.styleable.CommolySearchView_ClearIconMarginLeft, 0));
mClearIconMarginRight = px2dip(context, ta.getDimensionPixelOffset(
R.styleable.CommolySearchView_ClearIconMarginRight, 0));
mSearchTextSize = px2sp(context, ta.getDimensionPixelOffset(
R.styleable.CommolySearchView_SearchTextSize, 0));
mSearchTextColor = ta.getColor(R.styleable.CommolySearchView_SearchTextColor, 0);
ta.recycle();
LayoutInflater.from(context).inflate(R.layout.searchview_layout, this);
initView();
}
}
初始化時把自定義屬性套回控件:
private void initView() {
mEditText = (EditText) findViewById(R.id.et_search);
mClearImg = (ImageView) findViewById(R.id.iv_search_clear);
mSearchBarImg = (ImageView) findViewById(R.id.iv_search_icon);
if (0 != mSearchIconMarginLeft || 0 != mSearchIconMarginRight) {
mSearchBarImg.setPadding(mSearchIconMarginLeft, 0, mSearchIconMarginRight, 0);
}
if (0 != mClearIconMarginLeft || 0 != mClearIconMarginRight) {
mClearImg.setPadding(mClearIconMarginLeft, 0, mClearIconMarginRight, 0);
}
if (null != mSearchIcon) mSearchBarImg.setImageBitmap(mSearchIcon);
if (null != mClearIcon) mClearImg.setImageBitmap(mClearIcon);
if (0 != mSearchTextSize) mEditText.setTextSize(mSearchTextSize);
if (0 != mSearchTextColor) mEditText.setTextColor(mSearchTextColor);
mClearImg.setOnClickListener(new OnClickListener() {
@Override public void onClick(View view) {
mEditText.setText("");
mClearImg.setVisibility(View.GONE);
if (null != mDatas) {
mDatas.clear();
}
mDatas.addAll(mDupDatas); // 還原成完整資料
mAdapter.notifyDataSetChanged();
reSetDatas();
}
});
mEditText.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int a, int b, int c) { }
@Override public void onTextChanged(CharSequence s, int a, int b, int c) {
// 過濾交給外部回呼,元件只負責刷新
mFilterDatas = mListener.filterDatas(mDupDatas, mFilterDatas, s.toString());
mClearImg.setVisibility(s.toString().length() > 0 ? View.VISIBLE : View.GONE);
mDatas.clear();
mDatas.addAll(mFilterDatas);
mAdapter.notifyDataSetChanged();
reSetDatas();
}
@Override public void afterTextChanged(Editable editable) { }
});
}
這裡的設計取捨是:元件負責「何時過濾、如何刷新」,使用者負責「怎麼過濾」。介面定義如下:
public interface SearchDatas<T> {
/**
* @param datas 全部資料
* @param filterdatas 過濾結果容器
* @param inputstr 輸入內容
* @return 過濾後的資料
*/
List<T> filterDatas(List<T> datas, List<T> filterdatas, String inputstr);
}
private SearchDatas<T> mListener;
public void setSearchDataListener(SearchDatas<T> listener) {
mListener = listener;
}
對外只暴露三個方法:設定資料源、設定 Adapter、設定回呼。
public void setDatas(List<T> datas) {
if (null == datas) return;
if (null != mDatas) mDatas.clear();
if (null != mDupDatas) mDupDatas.clear();
mDatas = datas;
mDupDatas.addAll(mDatas); // 留一份原始備份,清除時才還原得回來
}
public void setAdapter(BaseAdapter adapter) {
if (null == adapter) return;
mAdapter = adapter;
}
/** 取得目前篩選後的資料,供點擊事件使用 */
public List<T> getFilterDatas() {
return (null != mDupFilterDatas && mDupFilterDatas.size() > 0) ? mDupFilterDatas : mDupDatas;
}
/** 重置篩選結果 */
private void reSetDatas() {
if (null != mFilterDatas) {
if (null != mDupFilterDatas) {
mDupFilterDatas.clear();
mDupFilterDatas.addAll(mFilterDatas);
}
mFilterDatas.clear();
}
}
另有兩個小工具方法:drawableToBitamp 把自定義屬性傳入的 Drawable 轉成 Bitmap(若本身就是 BitmapDrawable 則直接取用),以及 px 轉 dip / sp 的換算,避免不同解析度下尺寸跑掉。
資料物件很單純,這裡用三國人物當範例:
public class SanGuoBean {
private String sgName; // 姓名
private String sgDescribe; // 描述
private int sgHeadBp; // 頭像
private String sgPetName; // 字
// getter / setter 省略
}
Adapter 就是普通的 BaseAdapter 加 ViewHolder:
public class SGAdapter extends BaseAdapter {
private Context mContext;
private List<SanGuoBean> mDatas;
public SGAdapter(Context context, List<SanGuoBean> datas) {
mContext = context;
mDatas = datas;
}
@Override public int getCount() { return mDatas.size(); }
@Override public Object getItem(int i) { return mDatas.get(i); }
@Override public long getItemId(int i) { return i; }
@Override public View getView(int position, View view, ViewGroup viewGroup) {
ViewHolder vh;
if (null == view) {
vh = new ViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.sg_item, null);
vh.mNameTv = view.findViewById(R.id.tv_sgname);
vh.mPetNmaeTv = view.findViewById(R.id.tv_sgpetname);
vh.mDesTv = view.findViewById(R.id.tv_sgdes);
vh.mHeadImg = view.findViewById(R.id.iv_sghead);
view.setTag(vh);
} else {
vh = (ViewHolder) view.getTag();
}
SanGuoBean bean = getItem(position);
if (null != bean) {
vh.mNameTv.setText(bean.getSgName());
vh.mDesTv.setText(bean.getSgDescribe());
vh.mPetNmaeTv.setText(bean.getSgPetName());
vh.mHeadImg.setImageResource(bean.getSgHeadBp());
}
return view;
}
class ViewHolder {
TextView mNameTv, mDesTv, mPetNmaeTv;
ImageView mHeadImg;
}
}
版面中直接放自定義控件,並透過 search: 命名空間設定屬性:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:search="https://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.junweiliu.commonlysearchview.commolysearchview
android:id="@+id/csv_show"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="8dip"
android:background="@drawable/login_et_bg"
search:searchtextcolor="#ff0000"
search:searchtextsize="14sp" />
<ListView
android:id="@+id/lv_show"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Activity 中把三件事接起來即可:
private void initViewI() {
mSGCommolySearchView = findViewById(R.id.csv_show);
mListView = findViewById(R.id.lv_show);
sgAdapter = new SGAdapter(this, mSGDatas);
mListView.setAdapter(sgAdapter);
mSGCommolySearchView.setDatas(mSGDatas);
mSGCommolySearchView.setAdapter(sgAdapter);
mSGCommolySearchView.setSearchDataListener(new CommolySearchView.SearchDatas<SanGuoBean>() {
@Override public List<SanGuoBean> filterDatas(List<SanGuoBean> datas,
List<SanGuoBean> filterdatas,
String inputstr) {
for (int i = 0; i < datas.size(); i++) {
// 比對條件:描述、姓名、字任一命中即納入
if (datas.get(i).getSgDescribe().contains(inputstr)
|| datas.get(i).getSgName().contains(inputstr)
|| datas.get(i).getSgPetName().contains(inputstr)) {
filterdatas.add(datas.get(i));
}
}
return filterdatas;
}
});
// 點擊時要從「篩選後的清單」取值,否則索引會對不上
mListView.setOnItemClickListener((parent, view, i, l) -> {
SanGuoBean bean = mSGCommolySearchView.getFilterDatas().get(i);
Toast.makeText(MainActivity.this,
bean.getSgName() + "字" + bean.getSgPetName() + "\n" + bean.getSgDescribe(),
Toast.LENGTH_SHORT).show();
});
}
成果:
最後提醒一個實作時容易忽略的細節:ListView 的點擊監聽必須從 getFilterDatas() 取值,而不是從原始資料清單取。因為列表顯示的是過濾後的結果,若直接用原始清單的索引,過濾狀態下點到的就會是錯的項目。這個問題在資料量小、測試不仔細時幾乎不會發現,上線後卻很致命。
整體而言,這個元件把重複的部分(版面、清除按鈕、刷新時機)都收進去了,留下唯一真正因專案而異的部分——過濾規則——作為回呼交給呼叫方。換個資料型別、換個列表,都能直接複用。
Android 中的 TCP 與 UDP 通訊整理
之前寫過一些 TCP 與 UDP 的資料傳輸代碼,例如用 TCP 傳輸音視頻封包、在 P2P 打洞時使用 UDP。寫完就丟著沒整理,最近重新翻出來複習,索性把重點記錄下來
從鎖屏服務 AIDL 通信看 Android 底層啟動流程
從 SystemServer 說起在 Android 4.4 的啟動流程中,SystemServer 會負責啟動多個系統服務。其中,WindowManagerServic
Android 快速接入極光短信驗證服務:從申請 AppKey 到跑通驗證流程
先用 Android Studio 建立一個新的空專案,接著按下面的步驟走。 步驟一:取得 AppKey 登入極光官方平台,新建一個短信應用,依指示填寫套件名稱與應用名稱
Android 高擴展性適配器設計:用渲染器模式優雅處理多類型 Item
前言 本文帶大家體驗一種具有良好擴展性的適配器寫法。這種寫法特別適合 Item 有多種類型的場景,當然只有單一類型時同樣適用。核心思想是:把每個 Item 的渲染邏輯抽離