之前写过自定义加减控件的文章,大家可以看看
仿美团外卖自定义加减控件(二)
然后个人觉得将“加号事件”,“减号事件”和“输入事件”放一起处理不好,还是需要给个type来区分下比较好,此篇文章算是对仿美团外卖自定义加减控件(二)文章的一个优化吧。
下面就来具体讲讲代码的实现。
第一步,先上一个最低得输入一位数的输入框代码,ForbidenNumEditText
代码如下:
package com.test.ui.main;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import com.test.util.StringUtil;
/**
* Instruction:当edtText中的位数为1时,禁用删除键
* <p>
* Author:pei
* Date: 2017/7/26
* Description:
*/
public class ForbidenNumEditText extends android.support.v7.widget.AppCompatEditText{
public ForbidenNumEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* If you handled the event, return true <br>
* If you want to allow the event to be handled by the next receiver, return false.
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//屏蔽删除键(保留edittext最低位数为1)
if (keyCode == KeyEvent.KEYCODE_DEL) {
String content= ForbidenNumEditText.this.getText().toString();
if(StringUtil.isNotEmpty(content)&&content.length()==1){
return false;//不管返回false还是true都会把del键盘屏蔽,不同的是false会继续传入到Activity中
}
}
return super.onKeyDown(keyCode, event);
}
}
第二步,上自定义加减控件代码CicleAddAndSubView
package com.test.ui.main;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.test.R;
import com.test.util.KeyboardUtil;
/**
* Instruction:自定义加减数量控件
* <p>
* Author:pei
* Date: 2017/7/13
* Description:
*/
public class CicleAddAndSubView extends LinearLayout implements View.OnClickListener{
public static final int TYPE_SUBTRACT = 0;//减
public static final int TYPE_ADD = 1;//加
public static final int TYPE_INPUT =2;//输入框输入事件
private static final int DEFAULT_NUM=0;//默认num值
private static final int MAX_NUM=999;
private View mLayoutView;
private Context mContext;
private ImageView mBtnAdd;//加按钮
private ImageView mBtnSub;//减按钮
private EditText mEdtCount;//数量显示
private OnNumChangeListener mOnNumChangeListener;
private int mType=-1;
/**
* 设置监听回调
*
* @param onNumChangeListener
*/
public void setOnNumChangeListener(OnNumChangeListener onNumChangeListener) {
this.mOnNumChangeListener = onNumChangeListener;
}
public CicleAddAndSubView(Context context, AttributeSet attrs) {
super(context, attrs);
mLayoutView=LayoutInflater.from(context).inflate(R.layout.add_sub_view, this);
this.mContext=context;
initView();
initData();
setListener();
}
private void initView(){
mBtnAdd = (ImageView) mLayoutView.findViewById(R.id.btn_add);
mBtnSub = (ImageView) mLayoutView.findViewById(R.id.btn_sub);
mEdtCount = (ForbidenNumEditText) mLayoutView.findViewById(R.id.edt_count);
//重新设置mBtnAdd,mBtnSub宽高,用来保证显示正方形
setViewSize(mBtnAdd);
setViewSize(mBtnSub);
}
private void initData(){
setAddBtnImageResource(R.mipmap.ic_add_goods);
setSubBtnImageResource(R.mipmap.ic_sub_goods);
setNum(DEFAULT_NUM);//设置默认数量
}
private void setListener(){
mBtnAdd.setOnClickListener(this);
mBtnSub.setOnClickListener(this);
mEdtCount.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mType=TYPE_INPUT;
return false;
}
});
mEdtCount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//s:变化前的所有字符; start:字符开始的位置; count:变化前的总字节数;after:变化后的字节数
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//S:变化后的所有字符;start:字符起始的位置;before: 变化之前的总字节数;count:变化后的字节数
}
@Override
public void afterTextChanged(Editable s) {
//Editable s:变化后的所有字符
if (mOnNumChangeListener != null) {
mOnNumChangeListener.onNumChange(mLayoutView,mType,getNum());
}
}
});
}
private void setViewSize(final View view){
view.post(new Runnable(){
public void run() {//这里获取宽高
int width=view.getWidth();
int height=view.getHeight();
LayoutParams params= (LayoutParams) view.getLayoutParams();
if(width<height){
params.height=width;
}else if(width>height){
params.width=height;
}
view.setLayoutParams(params);
}
});
}
@Override
public void onClick(View v) {
//隐藏软键盘
KeyboardUtil.closeKeybord(v,mContext);
String countText = mEdtCount.getText().toString();
if (TextUtils.isEmpty(countText)) {
setNum(DEFAULT_NUM);
return;
}
int num=DEFAULT_NUM;
try {
num=Integer.valueOf(mEdtCount.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
}
switch(v.getId()){
case R.id.btn_add://加号
mType=TYPE_ADD;
if(num>=MAX_NUM){
num=MAX_NUM;
}else{
num++;
}
setNum(num);
break;
case R.id.btn_sub://减号
mType=TYPE_SUBTRACT;
num--;
setNum(num);
break;
default:
break;
}
}
/**
* 设置中间的距离
*
* @param distance
*/
public void setMiddleDistance(int distance) {
mEdtCount.setPadding(distance, 0, distance, 0);
}
/**
* 设置数量
*
* @param num
*/
public void setNum(int num) {
if (num > 0) {
mBtnSub.setVisibility(View.VISIBLE);
mEdtCount.setVisibility(View.VISIBLE);
} else {
mBtnSub.setVisibility(View.INVISIBLE);
mEdtCount.setVisibility(View.INVISIBLE);
}
mEdtCount.setText(String.valueOf(num));
//光标设置在结尾
mEdtCount.setSelection(mEdtCount.getText().length());
}
/**
* 获取值
*
* @return
*/
public int getNum() {
String countText=mEdtCount.getText().toString().trim();
if (!TextUtils.isEmpty(countText)) {
return Integer.parseInt(countText);
} else {
return DEFAULT_NUM;
}
}
/**
* 设置加号图片
*
* @param addBtnDrawable
*/
public void setAddBtnImageResource(int addBtnDrawable) {
mBtnAdd.setImageResource(addBtnDrawable);
}
/**
* 设置减法图片
*
* @param subBtnDrawable
*/
public void setSubBtnImageResource(int subBtnDrawable) {
mBtnSub.setImageResource(subBtnDrawable);
}
/**
* 设置加法减法的背景色
*
* @param addBtnColor
* @param subBtnColor
*/
public void setButtonBgColor(int addBtnColor, int subBtnColor) {
mBtnAdd.setBackgroundColor(addBtnColor);
mBtnSub.setBackgroundColor(subBtnColor);
}
public interface OnNumChangeListener {
/**
* 监听方法
*
* @param view
* @param num 返回的数值
*/
void onNumChange(View view, int type,int num);
}
}
涉及到的布局add_sub_view.xml代码如下:
<?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="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="@+id/btn_sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<com.test.ui.main.ForbidenNumEditText
android:id="@+id/edt_count"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:inputType="number"
android:gravity="center"
android:singleLine="true"
android:maxLines="1"
android:maxLength="3"
android:layout_margin="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="@drawable/add_sub_edt_bg"
android:text="0"
android:textColor="@color/black"
android:textSize="16sp"/>
<ImageView
android:id="@+id/btn_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
讲下CicleAddAndSubView的思路吧,我是设置加号,减号的点击事件,然后为了监听editText的输入事件,我在ForbidenNumEditText的onTouch事件上设置type值。最后,为了确保用户每次都去touch我们的ForbidenNumEditText,我在加号,减号事件中加入隐藏软键盘的代码。下面,为大家展示隐藏键盘的代码KeyboardUtil.java
第三步,隐藏键盘的代码
package com.test.util;
import android.app.Activity;
import android.content.Context;
import android.text.InputType;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 软键盘面的显示隐藏类
*
* @author pei
*/
public class KeyboardUtil {
/** 打开软键盘 **/
public static void openKeybord(View view, Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.RESULT_SHOWN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
/** 关闭软键盘 **/
public static void closeKeybord(View view, Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
/**
* 获取软件盘状态
* 若返回true,则表示输入法打开
* @param mContext
* @return
*/
public static boolean isKeybordOpen(Context mContext){
boolean isOpen=false;
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
isOpen=imm.isActive();//isOpen若返回true,则表示输入法打开
return isOpen;
}
/**如果有软键盘,那么隐藏它,反之,把它显示出来**/
public static void changeKeybord(Context mContext){
InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
//2.调用toggleSoftInput方法,实现切换显示软键盘的功能。
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
}
/** 隐藏系统如那件盘(根据sdk版本判断来隐藏软键盘,完全隐藏,再也不出现) **/
public static void hideSoftInputMethod(EditText ed, Activity activity) {
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
int currentVersion = android.os.Build.VERSION.SDK_INT;
String methodName = null;
if (currentVersion >= 16) {
// 4.2
methodName = "setShowSoftInputOnFocus";
} else if (currentVersion >= 14) {
// 4.0
methodName = "setSoftInputShownOnFocus";
}
if (methodName == null || currentVersion <= 10) {
ed.setInputType(InputType.TYPE_NULL);
} else {
Class<EditText> cls = EditText.class;
Method setShowSoftInputOnFocus;
try {
setShowSoftInputOnFocus = cls.getMethod(methodName, boolean.class);
setShowSoftInputOnFocus.setAccessible(true);
setShowSoftInputOnFocus.invoke(ed, false);
} catch (NoSuchMethodException e) {
ed.setInputType(InputType.TYPE_NULL);
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
第四步,在mainActivity的布局activity_main.xml中引用控件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">
<Button
android:id="@+id/btn_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:layout_gravity="center"
android:textSize="14sp"
android:text="测试"/>
<com.test.ui.main.CicleAddAndSubView
android:id="@+id/cicle_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
第五步,MainActivity中的使用代码
package com.test.ui.main;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import com.test.R;
import com.test.base.BaseActivity;
import com.test.base.BasePresenter;
import com.test.util.LogUtil;
import butterknife.BindView;
/**
* Created by Admin on 2017/5/19.
*/
public class MainActivity extends BaseActivity implements View.OnClickListener {
@BindView(R.id.btn_test)
Button mBtnTest;
@BindView(R.id.cicle_view)
CicleAddAndSubView mCicleView;
@Override
protected int getContentViewId() {
return R.layout.activity_main;
}
@Override
protected void initData() {
}
@Override
protected void setListener() {
mBtnTest.setOnClickListener(this);
mCicleView.setOnNumChangeListener(new CicleAddAndSubView.OnNumChangeListener() {
@Override
public void onNumChange(View view, int type, int num) {
switch(type){
case CicleAddAndSubView.TYPE_ADD:
LogUtil.e("=====add====="+num);
showShortToast("=====add====="+num);
break;
case CicleAddAndSubView.TYPE_SUBTRACT:
LogUtil.e("=====subtract====="+num);
showShortToast("=====subtract====="+num);
break;
case CicleAddAndSubView.TYPE_INPUT:
LogUtil.e("=====input====="+num);
showShortToast("=====input====="+num);
break;
default:
break;
}
}
});
}
@Nullable
@Override
protected BasePresenter getPresenter() {
return null;
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_test:
// Intent serviceIntent=new Intent(mContext,DownLoadService.class);
// serviceIntent.setAction("com.test.http.download.DownLoadService");
// startService(serviceIntent);
break;
case 1:
break;
default:
break;
}
}
}
最后,让我们来看看效果图吧
ok,今天的内容就讲到这里了,谢谢诶。