import android.app.Activity;
import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView; /**
*
* ModifyCountDialog ModifyCountDialog = new ModifyCountDialog.Builder(
* Activity.this,2030L).build();
* ModifyCountDialog.setModifyCountListener(new ModifyCountListener(){
* @Override
* public void onDelivered(long Count) {
* Log.d(TAG, "--------送你"+Count+"朵花");
* }
*
* });
* ModifyCountDialog.show();
*
*
*/
public class ModifyCountDialog extends popDialog implements OnClickListener
,OnTouchListener{ private static final String TAG = "ModifyCountDialog";
private static final int SCORE_PER_ = 10; // currentScore = totalScore - Count * SCORE_PER_ private Activity mActivity;
private String title; // title string, have default
// R.string.dialog_deliver__title
private long totalScore; // user total score private long mMaxCount = 0;
private long mCurrentCount = 0;
private long mCurrentScore; private Button mBtnCountSub;
private Button mBtnCountAdd; private TextView mTvScore;
private EditText mEditCount; // private boolean isButtonCountChange=false; public static class Builder {
private final Activity mActivity; private String title;
private long score; // user current score /**
* @param context
* @param score
*/
public Builder(Activity context, long score) {
this.mActivity = context;
this.score = score;
} public Builder title(String title) {
this.title = title;
return this;
} public ModifyCountDialog build() {
return new ModifyCountDialog(this);
}
} private ModifyCountDialog(Builder builder) {
super(builder.mActivity);
this.mActivity = builder.mActivity;
this.totalScore = builder.score; if (this.totalScore > 0) {
this.mMaxCount = (long) (this.totalScore / SCORE_PER_);
this.mCurrentScore = this.totalScore;
} if (!TextUtils.isEmpty(builder.title)) {
this.title = builder.title;
} initDialog();
} private void initDialog() {
View view = LayoutInflater.from(mActivity).inflate(
R.layout.dialog_deliver_, null, false); view.findViewById(R.id.btn_cancle).setOnClickListener(this);
view.findViewById(R.id.btn_deliver).setOnClickListener(this); mBtnCountSub = (Button) view
.findViewById(R.id.dialog_deliver__count_sub);
mBtnCountSub.setOnClickListener(this); mBtnCountAdd = (Button) view
.findViewById(R.id.dialog_deliver__count_add);
mBtnCountAdd.setOnClickListener(this); mTvScore = (TextView) view
.findViewById(R.id.dialog_deliver__score_tv);
mTvScore.setText(String.valueOf(totalScore)); mEditCount = (EditText) view
.findViewById(R.id.dialog_deliver__count); mEditCount.setOnTouchListener(this);   //set keyboard property, the dialog will push up getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);     this.build(view, true);
  }   @Override
  public boolean onTouch(View v, MotionEvent event) {
    if(v.getId()==R.id.dialog_deliver_flower_count) {
      mEditFlowerCount.selectAll(); //select all character in EditText
      showKeyboard(mEditFlowerCount); //without calling this. keyboard hide
      return true;
    }
    return false;
  }   private boolean isCountLegal(long count){
return (count >=0)&&(count <= mMaxCount);
} /**
* EditText text change watcher
*
* when user input is illegal, setText to 0 or MaxCount
*
* warn: call setText() in wrong place, will cause infinite loop and StackOverFlow
*
*/
TextWatcher mTextWatcher = new TextWatcher() {
private long mCount;
@Override
public void onTextChanged(CharSequence s, int start, int before,int count) { } @Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) { } @Override
public void afterTextChanged(Editable s) {
String str = s.toString();
// Log.d(TAG, "---myc---afterTextChanged str------" + str);
if(!TextUtils.isEmpty(str) && TextUtils.isDigitsOnly(str)){
mCount = Long.parseLong(str);
}else{
mCount = 0;
} //if user input is illegal, set to legal count
if(!isCountLegal(mCount)){
if(mCount < 0){
mCount = 0;
}else if(mCount > mMaxFlowerCount){
mCount = mMaxFlowerCount;
}
mEditFlowerCount.setText(String.valueOf(mCount)); //illegal, set to 0 or maxFlowerCount
mEditFlowerCount.selectAll();
}
setCurrentFlowerCount(mCount);
}
}; /**
* getter
*
* @return
*/
public long getCurrentCount() {
return this.mCurrentCount;
} /**
* setter
*
* @return
*/
public void setCurrentCount(long Count) {
if(isCountLegal(Count) && Count!=mCurrentCount){
Log.d(TAG, "---setCurrentCount------" + Count);
this.mCurrentCount = Count;
refreshUI(Count);
}
} ModifyCountListener mModifyCountListener; public interface ModifyCountListener { //在Activity里弹框获取用户输入,可以通过回调的方法来获取用户输入值
void onModified(long Count);
} public void setModifyCountListener(ModifyCountListener listener) {
mModifyCountListener = listener;
} /**
* user press "modify" button
*
*/
private void doModifyCount() {
if (mModifyCountListener != null) {
mModifyCountListener.onModified(mCurrentCount);    //将值回调给Activity
}
} /**
* refresh EditText, current core TextView and so on
*
* @param Count
*/
private void refreshUI(long Count) {
mCurrentScore = totalScore - Count * SCORE_PER_; if (mCurrentScore >= 0) {
mTvScore.setText(String.valueOf(mCurrentScore));
} if (Count <= 0) {
setBtnClickable(false, true);
} else if (Count >= mMaxCount) {
setBtnClickable(true, false);
} else {
setBtnClickable(true, true);
}
} /**
* hide keyboard
*
* @param v
*/
private void hideKeyboard(View v) {
// Log.d(TAG, "---hideKeyboard()------");
if(v == null){
return;
}
InputMethodManager imm = (InputMethodManager) v.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
} /**
* show keyboard
*
* @param v
*/
private void showKeyboard(View v) {
// Log.d(TAG, "---showKeyboard()------");
if(v == null){
return;
}
InputMethodManager imm = (InputMethodManager) v.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(v, 0);
} /**
* set Button Clickable
*
* @param canSub
* if true, can sub count
* @param canAdd
* if true, can add count
*/
private void setBtnClickable(boolean canSub, boolean canAdd) {
mBtnCountSub.setClickable(canSub);
mBtnCountAdd.setClickable(canAdd);
} @Override
public void onClick(View view) {
if(!view.equals(R.id.dialog_deliver__count))      
{
hideKeyboard(mEditCount);
}
   switch (view.getId()) {
case R.id.btn_cancle:
this.dismiss();
break;
case R.id.btn_deliver:
doModifyCount();
this.dismiss();
break;
case R.id.count_sub:
if (mCurrentCount > 0) {
setCurrentCount(mCurrentCount - 1);
mEditCount.setText(String.valueOf(mCurrentCount));
}
break;
case R.id.count_add:
if (getCurrentCount() < mMaxCount) {
setCurrentCount(getCurrentCount() + 1);
mEditCount.setText(String.valueOf(mCurrentCount));
}
break;
default:
break;
}
}
}

包括

(1)隐藏  和 弹出键盘

     /**
* hide keyboard
*
* @param v
*/
private void hideKeyboard(View v) {
// Log.d(TAG, "---hideKeyboard()------");
if(v == null){
return;
}
InputMethodManager imm = (InputMethodManager) v.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
} /**
* show keyboard
*
* @param v
*/
private void showKeyboard(View v) {
// Log.d(TAG, "---showKeyboard()------");
if(v == null){
return;
}
InputMethodManager imm = (InputMethodManager) v.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(v, 0);
}

(2)防止键盘挡住输入框

         //set keyboard property, the dialog will push up  防止EditText被挡住, 往上推Dialog
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |  
WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

(3)点击EditText以外的区域,隐藏键盘,注意父view要设置onClickListener

parentView.setOnClickListener(this); 

@Override
public void onClick(View view) {
if(!view.equals(R.id.dialog_deliver__count))      
{
hideKeyboard(mEditCount);
}
}

本来想在 EditText OnFocusListener()里监听, 失去焦点后,隐藏键盘. 不起作用

因为对话框弹出的时候, EditText的isFocused是true的。除非点击按钮等,才会失去焦点。但是现在是想点击任何区域都失去焦点。

所以需要通过监听整个父控件

(4) 监听EditText输入

官方文档也指出:千万注意别在三个方法里随意重复调用setText,会死循环
mEditCount.addTextChangedListener(mTextWatcher);        //先给EditText设置监听
    /**
* EditText text change watcher                  
*
* when user input is illegal, setText to 0 or MaxCount    
*
* warn: call setText() in wrong place, will cause infinite loop and StackOverFlow  
*
*/
TextWatcher mTextWatcher = new TextWatcher() {
private long mCount;
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) { } @Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) { } @Override
public void afterTextChanged(Editable s) {
String str = s.toString();
// Log.d(TAG, "---afterTextChanged str------" + str); if(!TextUtils.isEmpty(str) && TextUtils.isDigitsOnly(str)){
mCount = Long.parseLong(str);
}else{
mCount = 0;
} //if user input is illegal, set to legal count
if(!isCountLegal(mCount)){
if(mCount < 0){
mCount = 0;
}else if(mCount > mMaxCount){
mCount = mMaxCount;
}
mEditCount.setText(String.valueOf(mCount)); //illegal, set to 0 or maxCount
mEditCount.selectAll(); //如果设置成最大值以后不全选,再点一个数字.s比最大值还大,EditText没反                                          //应,看起来就像失去焦点了. 但事实上调用 isFocused判断时, 还是有焦点的
}
setCurrentCount(mCount);
}
};
(5)全选一个输入框的内容
     @Override
public boolean onTouch(View v, MotionEvent event) {
if(v.getId()==R.id.dialog_deliver__count) {
mEditCount.selectAll(); //全选EditText的内容
showKeyboard(mEditCount); //全选完如果不调用这个,不弹出键盘
return true;
}
return false;
}
 

Android 自定义带回调的Dialog 及EditText相关的更多相关文章

  1. Android 自定义带刻度的seekbar

    自定义带刻度的seekbar 1.布局 <span style="font-family:SimHei;font-size:18px;"><com.imibaby ...

  2. Android自定义View带有删除按钮的EditText

    转载请注明出处http://blog.csdn.net/xiaanming/article/details/11066685 今天给大家带来一个很实用的小控件ClearEditText,就是在Andr ...

  3. Android自定义带标题边框的Layout

    今天工作中又碰到个小问题,项目需要用到像Java Swing的JPanel一样带标题边框的布局,Android里没有类似控件,想到这个也不难,自己画了一个,是继承LinearLayout的一个自定义布 ...

  4. Android -- 自定义带进度条的按钮

    1. 实现了一个带进度条的按钮,完成后显示提示信息,并设置按钮为不可再次被点击

  5. android 自定义alertdialog和取消dialog

    看代码: public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle ...

  6. 35.Android之带删除按钮EditText学习

    今天实现Android里自定义带删除功能的EditText,效果如下: 当输入内容时,EditText变为带有一个删除功能按钮的编辑框,如图: 实现代码很简单,直接上代码, 布局文件xml: < ...

  7. [置顶] xamarin android自定义标题栏(自定义属性、回调事件)

    自定义控件的基本要求 这篇文章就当是自定义控件入门,看了几篇android关于自定义控件的文章,了解了一下,android自定义控件主要有3种方式: 自绘控件:继承View类,所展示的内容在OnDra ...

  8. Android自定义底部带有动画的Dialog

    Android自定义底部带有动画的Dialog 效果图 先看效果图,是不是你想要的呢 自定义Dialog package --.view; import android.app.Dialog; imp ...

  9. 我的Android进阶之旅------>Android自定义View实现带数字的进度条(NumberProgressBar)

    今天在Github上面看到一个来自于 daimajia所写的关于Android自定义View实现带数字的进度条(NumberProgressBar)的精彩案例,在这里分享给大家一起来学习学习!同时感谢 ...

随机推荐

  1. PrintWriter的使用

    java.io.PrintWriter 具有自动行刷新的缓冲字符输出流,特点是可以按行写出字符串,并且可以自动行刷新. java.io.BufferedWriter是缓冲字符输出流,内部有缓冲区可以进 ...

  2. CSS之动态相册

    注释还是比较详细的,所以我就不一一再说明了.--->运行效果图<--- (点击之前温馨提示一下:此picture是我自己的照片,本来不想拿出来的,后来觉得反正不会有很多人看到而且也没人认识 ...

  3. Memcache简介 & 内存分配机制

            关于这个东西里面到底应该存放数据网上一直有很多种说法,有的说sql进行md5之后作为键值,结果作为内容存放,也有人说按照业务逻辑错放,反正是炒的不亦乐乎.        本人经过将近2 ...

  4. vmware centos 连网方式

    1.自动获取IP地址 虚拟机使用桥接模式,相当于连接到物理机的网络里,物理机网络有DHCP服务器自动分配IP地址. #dhclient 自动获取ip地址命令 #ifconfig 查询系统里网卡信息,i ...

  5. 2018.7.28 A murder that scandalised Harvard and the world

    A murder that scandalised Harvard and the worldVisiting Boston in 1868, Charles Dickens was asked wh ...

  6. Codeforces Round #254(div2)B

    就是看无向图有几个连通块,答案就是2n-num. 范围很小,就用矩阵来存图减少代码量. #include<iostream> #include<cstdio> #include ...

  7. Zeroc Ice 发布订阅者之demo Icestorm之clock

    刚刚在服务端(192.168.0.113)和客户端跑通(192.168.0.188),在这里记录,作为备忘. 第一步:读readme,先用vs2010生成subscriber.exe和publishe ...

  8. nginx中关于并发数的问题worker_connections,worker_processes

    我认为,要搞清楚这个公式是否正确,以及如何计算的,那首先要对nginx的各个配置说明有清晰的认识: 从用户的角度,http 1.1协议下,由于浏览器默认使用两个并发连接,因此计算方法: nginx作为 ...

  9. LeetCode Max Consecutive Ones II

    原题链接在这里:https://leetcode.com/problems/max-consecutive-ones-ii/ 题目: Given a binary array, find the ma ...

  10. FastAdmin 推荐 Git 在线学习教程

    FastAdmin 推荐 Git 在线学习教程 因为 FastAdmin 推荐使用 Git 管理代码,有很多小伙伴对 Git 不是很熟悉. 也苦于找不到好的教程,我就分享一个 Git 在线学习教程. ...