开发中经常需要为用户提供一个单独的搜索页面,这里做一下记录。
先贴上最终的效果:
1.输入框背景,通过定义drawable实现:
2.布局文件:
3.代码
public class SearchActivity extends BaseActivity implements TextWatcher, TextView.OnEditorActionListener { private static final String TAG = SearchActivity.class.getSimpleName(); private EditText mEditTextSearch; private TextView mTextViewDoSearch; private ImageView mImageViewClear; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mEditTextSearch.addTextChangedListener(this); mEditTextSearch.setOnEditorActionListener(this); mTextViewDoSearch.setOnClickListener(this); mImageViewClear.setOnClickListener(this); mEditTextSearch.setInputType(InputType.TYPE_CLASS_NUMBER); } @Override public void initView() { setContentView(R.layout.activity_search_bed); mEditTextSearch = (EditText) findViewById(R.id.title_bar_search_et); mTextViewDoSearch = (TextView) findViewById(R.id.title_bar_right_text); mImageViewClear = (ImageView) findViewById(R.id.title_bar_iv_clear); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { Log.d(TAG, "beforeTextChanged() s==" + s); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { Log.d(TAG, "onTextChanged() s==" + s); } @Override public void afterTextChanged(Editable s) { Log.d(TAG, "afterTextChanged() s==" + s); String content = s.toString().trim(); if (TextUtils.isEmpty(content)) { mTextViewDoSearch.setText("取消"); mImageViewClear.setVisibility(View.GONE); } else { mTextViewDoSearch.setText("搜索"); mImageViewClear.setVisibility(View.VISIBLE); } } @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { Log.d(TAG, "onEditorAction() content==" + v.getText()); return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.title_bar_right_text: if ("取消".equals(((TextView) v).getText().toString())) { onBackPressed(); } else { //搜索操作 } break; case R.id.title_bar_iv_clear: mEditTextSearch.setText(""); break; } super.onClick(v); }}