Home Java javaTutorial Android custom View soft keyboard to implement search

Android custom View soft keyboard to implement search

Jan 07, 2017 am 11:52 AM

1. xml文件中加入自定义 搜索view

<com.etoury.etoury.ui.view.IconCenterEditText
      android:id="@+id/search_et"
      style="@style/StyleEditText"
      android:hint="搜索景点信息"
      />
Copy after login

2. 自定义的 view java文件

IconCenterEditText.java
package com.etoury.etoury.ui.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public class IconCenterEditText extends EditText implements View.OnFocusChangeListener, View.OnKeyListener {
  private static final String TAG = IconCenterEditText.class.getSimpleName();
  /**
   * 是否是默认图标再左边的样式
   */
  private boolean isLeft = false;
  /**
   * 是否点击软键盘搜索
   */
  private boolean pressSearch = false;
  /**
   * 软键盘搜索键监听
   */
  private OnSearchClickListener listener;
  public void setOnSearchClickListener(OnSearchClickListener listener) {
    this.listener = listener;
  }
  public IconCenterEditText(Context context) {
    this(context, null);
    init();
  }
  public IconCenterEditText(Context context, AttributeSet attrs) {
    this(context, attrs, android.R.attr.editTextStyle);
    init();
  }
  public IconCenterEditText(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
  }
  private void init() {
    setOnFocusChangeListener(this);
    setOnKeyListener(this);
  }
  @Override
  protected void onDraw(Canvas canvas) {
    if (isLeft) { // 如果是默认样式,则直接绘制
      super.onDraw(canvas);
    } else { // 如果不是默认样式,需要将图标绘制在中间
      Drawable[] drawables = getCompoundDrawables();
      Drawable drawableLeft = drawables[0];
      Drawable drawableRight = drawables[2];
      translate(drawableLeft, canvas);
      translate(drawableRight, canvas);
//      if (drawableLeft != null) {
//        float textWidth = getPaint().measureText(getHint().toString());
//        int drawablePadding = getCompoundDrawablePadding();
//        int drawableWidth = drawableLeft.getIntrinsicWidth();
//        float bodyWidth = textWidth + drawableWidth + drawablePadding;
//
//        canvas.translate((getWidth() - bodyWidth - getPaddingLeft() - getPaddingRight()) / 2, 0);
//      }
//      if (drawableRight != null) {
//        float textWidth = getPaint().measureText(getHint().toString()); // 文字宽度
//        int drawablePadding = getCompoundDrawablePadding(); // 图标间距
//        int drawableWidth = drawableRight.getIntrinsicWidth(); // 图标宽度
//        float bodyWidth = textWidth + drawableWidth + drawablePadding;
//        setPadding(getPaddingLeft(), getPaddingTop(), (int)(getWidth() - bodyWidth - getPaddingLeft()), getPaddingBottom());
//        canvas.translate((getWidth() - bodyWidth - getPaddingLeft()) / 2, 0);
//      }
      super.onDraw(canvas);
    }
  }
  public void translate(Drawable drawable, Canvas canvas) {
    if (drawable != null) {
      float textWidth = getPaint().measureText(getHint().toString());
      int drawablePadding = getCompoundDrawablePadding();
      int drawableWidth = drawable.getIntrinsicWidth();
      float bodyWidth = textWidth + drawableWidth + drawablePadding;
      if (drawable == getCompoundDrawables()[0]) {
        canvas.translate((getWidth() - bodyWidth - getPaddingLeft() - getPaddingRight()) / 2, 0);
      } else {
        setPadding(getPaddingLeft(), getPaddingTop(), (int)(getWidth() - bodyWidth - getPaddingLeft()), getPaddingBottom());
        canvas.translate((getWidth() - bodyWidth - getPaddingLeft()) / 2, 0);
      }
    }
  }
  @Override
  public void onFocusChange(View v, boolean hasFocus) {
    Log.d(TAG, "onFocusChange execute");
    // 恢复EditText默认的样式
    if (!pressSearch && TextUtils.isEmpty(getText().toString())) {
      isLeft = hasFocus;
    }
  }
  @Override
  public boolean onKey(View v, int keyCode, KeyEvent event) {
    pressSearch = (keyCode == KeyEvent.KEYCODE_ENTER);
    if (pressSearch && listener != null) {
      /*隐藏软键盘*/
      InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
      if (imm.isActive()) {
        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
      }
      listener.onSearchClick(v);
    }
    return false;
  }
  public interface OnSearchClickListener {
    void onSearchClick(View view);
  }
}
Copy after login


3. style

</style> 
      <style name="StyleEditText">
      <item name="android:layout_width">match_parent</item>
      <item name="android:layout_height">wrap_content</item>
      <item name="android:background">@drawable/bg_search_bar</item>
      <item name="android:drawablePadding">5dp</item>
      <item name="android:gravity">center_vertical</item>
      <item name="android:imeOptions">actionSearch</item>
      <item name="android:drawableLeft">@drawable/icon_search</item>
      <item name="android:padding">5dp</item>
      <item name="android:singleLine">true</item>
      <item name="android:textColorHint">@color/grey</item>
      <item name="android:textSize">16sp</item>
      <item name="android:hint">搜索</item>
    </style>
Copy after login

4. bg_search_bar.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="@android:color/white" />
  <stroke
    android:width="1px"
    android:color="@android:color/darker_gray" />
  <corners android:radius="3dp" />
</shape>
Copy after login

5. activity 中加上代码

private IconCenterEditText search_et;
search_et = (IconCenterEditText) findViewById(R.id.search_et);
search_et.setOnSearchClickListener(new OnSearchClickListener() {
      @Override
      public void onSearchClick(View view) {
        // TODO Auto-generated method stub
        String texts = search_et.getText().toString().trim();
        if ("".equals(texts)) {
          ToastUtil.showToast("请输入您要搜索的内容");
        } else {
          //根据你的文字内容实现跳转          Intent intent = new Intent(context,
              SearchWordActivity.class);
          // intent.putExtra("searchMode", 1);
          intent.putExtra("searchWord", texts);
          context.startActivity(intent);
        }
      }
    });
Copy after login

   

以上内容是小编给大家介绍的Android自定义View软键盘实现搜索,希望大家喜欢。

更多Android自定义View软键盘实现搜索相关文章请关注PHP中文网!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles