温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中怎么自定义一个数字键盘

发布时间:2021-06-28 16:45:21 来源:亿速云 阅读:140 作者:Leah 栏目:移动开发

这篇文章给大家介绍Android中怎么自定义一个数字键盘,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1. 实现键盘的 xml 布局

网格样式的布局用 GridView 或者 RecyclerView 都可以实现,其实用 GridView 更方便一些,不过我为了多熟悉 RecyclerView 的用法,这里选择用了 RecyclerView。

<?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="wrap_content"
       android:orientation="vertical">

  <View
    android:layout_width="match_parent"
    android:layout_height="2px"
    android:background="@color/btn_gray"/>

  <RelativeLayout
    android:id="@+id/rl_back"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/iv_back_bg"
    android:padding="10dp">

    <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:src="@mipmap/keyboard_back"/>
  </RelativeLayout>

  <View
    android:layout_width="match_parent"
    android:layout_height="1px"
    android:background="@color/btn_gray"/>

  <android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/keyboard_bg"
    android:overScrollMode="never"></android.support.v7.widget.RecyclerView>

</LinearLayout>

RecyclerView 用来实现键盘布局,上面的 RelativeLayout 则是为了实现收起键盘的点击事件。

2. 在代码中实现键盘布局,填充数据、增加点击事件

我们新建类 KeyboardView 继承自 RelativeLayout,关联上面的布局文件,然后做一些初始化操作:对 RecyclerView 填充数据、设置适配器,设置出现和消失的动画效果,写一些会用到的方法等。

public class KeyboardView extends RelativeLayout {

  private RelativeLayout rlBack;
  private RecyclerView recyclerView;
  private List<String> datas;
  private KeyboardAdapter adapter;
  private Animation animationIn;
  private Animation animationOut;


  public KeyboardView(Context context) {
    this(context, null);
  }

  public KeyboardView(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
  }

  public KeyboardView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context, attrs, defStyleAttr);
  }

  private void init(Context context, AttributeSet attrs, int defStyleAttr) {
    LayoutInflater.from(context).inflate(R.layout.layout_key_board, this);
    rlBack = findViewById(R.id.rl_back);
    rlBack.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View view) { // 点击关闭键盘
        dismiss();
      }
    });
    recyclerView = findViewById(R.id.recycler_view);

    initData();
    initView();
    initAnimation();
  }

  // 填充数据
  private void initData() {
    datas = new ArrayList<>();
    for (int i = 0; i < 12; i++) {
      if (i < 9) {
        datas.add(String.valueOf(i + 1));
      } else if (i == 9) {
        datas.add(".");
      } else if (i == 10) {
        datas.add("0");
      } else {
        datas.add("");
      }
    }
  }

  // 设置适配器
  private void initView() {
    recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
    adapter = new KeyboardAdapter(getContext(), datas);
    recyclerView.setAdapter(adapter);
  }

  // 初始化动画效果
  private void initAnimation() {
    animationIn = AnimationUtils.loadAnimation(getContext(), R.anim.keyboard_in);
    animationOut = AnimationUtils.loadAnimation(getContext(), R.anim.keyboard_out);
  }

  // 弹出软键盘
  public void show() {
    startAnimation(animationIn);
    setVisibility(VISIBLE);
  }

  // 关闭软键盘
  public void dismiss() {
    if (isVisible()) {
      startAnimation(animationOut);
      setVisibility(GONE);
    }
  }

  // 判断软键盘的状态
  public boolean isVisible() {
    if (getVisibility() == VISIBLE) {
      return true;
    }
    return false;
  }

  public void setOnKeyBoardClickListener(KeyboardAdapter.OnKeyboardClickListener listener) {
    adapter.setOnKeyboardClickListener(listener);
  }

  public List<String> getDatas() {
    return datas;
  }

  public RelativeLayout getRlBack() {
    return rlBack;
  }
}

Adapter 里面都是很简单的代码,这里就不贴出了,文章末尾我会给出源码下载地址。

到这里为止,自定义数字键盘基本就算写好了,不过最重要的还是要和 Edittext 结合使用。

3. 与 Edittext 结合使用

1. 禁用系统软键盘

if (Build.VERSION.SDK_INT <= 10) {
   etInput.setInputType(InputType.TYPE_NULL);
} else {
   getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
   try {
     Class<EditText> cls = EditText.class;
     Method setShowSoftInputOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
     setShowSoftInputOnFocus.setAccessible(true);
     setShowSoftInputOnFocus.invoke(etInput, false);
   } catch (Exception e) {
     e.printStackTrace();
   }
}

在网上找了一些方法,但是点击 Edittext 的时候系统软键盘依然会弹出。最后找到了这个方法,利用反射强制不弹出软键盘,效果不错。

2. 处理各个按键的点击事件

  @Override
  public void onKeyClick(View view, RecyclerView.ViewHolder holder, int position) {
    switch (position) {
      case 9: // 按下小数点
        String num = etInput.getText().toString().trim();
        if (!num.contains(datas.get(position))) {
          num += datas.get(position);
          etInput.setText(num);
          etInput.setSelection(etInput.getText().length());
        }
        break;
      default: // 按下数字键
        if ("0".equals(etInput.getText().toString().trim())) { // 第一个数字按下0的话,第二个数字只能按小数点
          break;
        }
        etInput.setText(etInput.getText().toString().trim() + datas.get(position));
        etInput.setSelection(etInput.getText().length());
        break;
    }
  }

  @Override
  public void onDeleteClick(View view, RecyclerView.ViewHolder holder, int position) {
    // 点击删除按钮
    String num = etInput.getText().toString().trim();
    if (num.length() > 0) {
      etInput.setText(num.substring(0, num.length() - 1));
      etInput.setSelection(etInput.getText().length());
    }
  }

关于Android中怎么自定义一个数字键盘就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI