Android编程实现在自定义对话框中获取EditText中数据的方法

本文实例讲述了Android编程实现在自定义对话框中获取EditText中数据的方法。分享给大家供大家参考,具体如下:

在项目中忽然遇到这样的问题,需要自定义对话框,对话框需要有一个输入框,以便修改所选中的价格,然后点击确定之后,修改所显示的价格。遇到的最大的问题就是如何能够获取到自定义对话框当中edittext输入的数值,百度了很久,看到的答案都是如下:

//得到自定义对话框
final View DialogView = a .inflate ( R.layout.loand, null);

这是关键的代码

//创建对话框
AlertDialog dlg = new AlertDialog.Builder(loand.this)
.setTitle("登录框")
.setView(DialogView)//设置自定义对话框的样式
.setPositiveButton("登陆", //设置"确定"按钮
new DialogInterface.OnClickListener() //设置事件监听
{
  public void onClick(DialogInterface dialog, int whichButton)
  {
   editText1 =(EditText) DialogView.findViewById(R.id.editText1);
   editText2 =(EditText) DialogView.findViewById(R.id.editText2);
   String id = editText1.getText().toString();
   String password = editText2.getText().toString();
   //输入完成后,点击“确定”开始登陆
   c_log judge = new c_log();
   boolean b_judge = judge.aa(id,password);
   if(b_judge){
   bar();
   }else{
//加东西
   DisplayToast("NO");
   }
  }
})

上述方法对于使用系统自带的alertdialog来说,的确是没有问题,能够取到你输入的edittext的值,但对于自定义的alertdialog来说,就会始终拿到的是空的,我的解决方案是在自定义alertdialog里面取到edittext并且实例化,避免在activity里面进行初始化,步骤如下:

1.主要的activity主类代码:

package client.verbank.mtp.allone.frame.systemsettings;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;
import client.verbank.mtp.allone.R;
import client.verbank.mtp.allone.component.CustomDialogPriceModify;
import client.verbank.mtp.allone.consts.IBundleCommData;
import client.verbank.mtp.allone.consts.ISystemCommData;
import client.verbank.mtp.allone.frame.ControlFragment;
import client.verbank.mtp.allone.frame.MainActivity;
import client.verbank.mtp.allone.frame.systemsettings.nextpage.ChangePasswordActivity;
import client.verbank.mtp.allone.frame.systemsettings.nextpage.ChangePhonePinActivity;
import client.verbank.mtp.allone.frame.systemsettings.nextpage.ChooseRssActivity;
import client.verbank.mtp.allone.frame.systemsettings.nextpage.SelectInstrumentActivity;
import client.verbank.mtp.allone.util.SharepreferencesUtilSystemSettings;
/**
 * 系统设置界面
 *
 * @Project: FEIB_AndroidStation
 * @Title: SystemSettingsFragment.java
 * @Package client.verbank.mtp.allone.frame.systemsettings
 * @Description: TODO
 * @author qiulinhe qiu.linhe@allone.cn
 * @date 2015年9月29日 上午11:48:53
 * @Copyright: 2015 www.allone.cn Inc. All rights reserved.
 * @version V3.0.0
 */
public class SystemSettingsFragment extends ControlFragment implements
    ISystemCommData {
  // 四组需要打钩的textview初始化
  private TextView currencypairs;
  private TextView openpositionprice;
  private TextView floatingprofit;
  private TextView dealtime;
  private TextView ordercurrencypairs;
  private TextView pricehighend;
  private TextView priceendhigh;
  private TextView summarycurrencypairs;
  private TextView summaryfloatingprofit;
  private TextView riseandfall;
  private TextView applies;
  // 三个自定义输入金额
  private TextView inputamount2;
  private TextView inputamount5;
  private TextView inputamount10;
  // 跳转到下一个页面的4个textview,货币对选择、密码修改、凭证密码修改、RSS源选择
  private TextView Currencyofchoice;
  private TextView changepassword;
  private TextView changecertificatepassword;
  private TextView rsssource;
  ToggleButton mosthightoggle;
  ToggleButton mostlowtoggle;
  ToggleButton riseandfallmenutoggle;
  ToggleButton pricetimetoggle;
  View layout;
  // EditText price;
  AlertDialog dlg;
  int flagprice = 0;
  private Handler handler = new Handler();
  public SystemSettingsFragment(MainActivity activity) {
    super(activity);
  }
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View vi = inflater.inflate(R.layout.system_settings, container, false);
    // 价格修改弹出对话框
    layout = inflater.inflate(
        R.layout.activity_systemsettings_pricecustom_dialog,
        (ViewGroup) vi.findViewById(R.id.dialog));
  //。。。。。。。。。。省略了部分代码,因为是公司项目的。。。。。。。。。。。。。。
  // 三个自定义金额的监听事件
  private void selfThreeMoneyLister(View vi) {
    inputamount2.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        modifyPriceDialog();
        flagprice = 1;
      }
    });
    inputamount5.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        modifyPriceDialog();
        flagprice = 2;
      }
    });
    inputamount10.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        modifyPriceDialog();
        flagprice = 3;
      }
    });
  }
  // 点击价格,弹出编辑框,对价格进行修改
  private void modifyPriceDialog() {
    LayoutInflater factory = LayoutInflater.from(getActivity());
    final View DialogView = factory.inflate(
        R.layout.activity_systemsettings_pricecustom_dialog, null);
    final CustomDialogPriceModify.Builder builder = new CustomDialogPriceModify.Builder(
        getActivity());
    builder.setTitle("價格修改");
    builder.setPositiveButton(R.string.confirm,
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            // 获取edittext的值
            String priceStr = builder.getPrice();//关键代码,getPrice放在自定义的alertdialog类里面,进行初始化
            if (flagprice == 1) {
              inputamount2.setText(priceStr);
              SharepreferencesUtilSystemSettings.putValue(
                  getActivity(), System_key_SelfAmout2,
                  priceStr);
            } else if (flagprice == 2) {
              inputamount5.setText(priceStr);
              SharepreferencesUtilSystemSettings.putValue(
                  getActivity(), System_key_SelfAmout5,
                  priceStr);
            } else {
              inputamount10.setText(priceStr);
              SharepreferencesUtilSystemSettings.putValue(
                  getActivity(), System_key_SelfAmout10,
                  priceStr);
            }
            // price.setText("");
            /**
             * 取得view的父组件,然后移除view
             */
            dialog.dismiss();
          }
        });
    builder.setNegativeButton(R.string.cancel,
        new android.content.DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            // ((ViewGroup) layout.getParent()).removeView(layout);
            dialog.dismiss();
          }
        });
    builder.create().show();
  }
}

2.自定义alertdialog类,CustomDialogPriceModify.java,如下:

package client.verbank.mtp.allone.component;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import client.verbank.mtp.allone.R;
/**
 * 系统设定中修改价格的弹出对话窗口
 *
 * @author wangyubo
 *
 */
public class CustomDialogPriceModify extends Dialog {
  public CustomDialogPriceModify(Context context) {
    super(context);
  }
  public CustomDialogPriceModify(Context context, int theme) {
    super(context, theme);
  }
  public static class Builder {
    private Context context;
    private String title;
    private float textSize;
    private String message;
    private String positiveButtonText;
    private String negativeButtonText;
    private View contentView;
    private EditText priceText;
    private DialogInterface.OnClickListener positiveButtonClickListener;
    private DialogInterface.OnClickListener negativeButtonClickListener;
    public Builder(Context context) {
      this.context = context;
    }
    public Builder setMessage(String message) {
      this.message = message;
      return this;
    }
    public Builder setMessage(String message, float textSize) {
      this.message = message;
      this.textSize = textSize;
      return this;
    }
    /**
     * Set the Dialog message from resource
     *
     * @param title
     * @return
     */
    public Builder setMessage(int message) {
      this.message = (String) context.getText(message);
      return this;
    }
    /**
     * Set the Dialog title from resource
     *
     * @param title
     * @return
     */
    public Builder setTitle(int title) {
      this.title = (String) context.getText(title);
      return this;
    }
    /**
     * Set the Dialog title from String
     *
     * @param title
     * @return
     */
    public Builder setTitle(String title) {
      this.title = title;
      return this;
    }
    public Builder setContentView(View v) {
      this.contentView = v;
      return this;
    }
    /**
     * Set the positive button resource and it's listener
     *
     * @param positiveButtonText
     * @return
     */
    public Builder setPositiveButton(int positiveButtonText,
        DialogInterface.OnClickListener listener) {
      this.positiveButtonText = (String) context
          .getText(positiveButtonText);
      this.positiveButtonClickListener = listener;
      return this;
    }
    //关键代码
    public String getPrice() {
      return priceText.getText().toString();
    }
    public Builder setPositiveButton(String positiveButtonText,
        DialogInterface.OnClickListener listener) {
      this.positiveButtonText = positiveButtonText;
      this.positiveButtonClickListener = listener;
      return this;
    }
    public Builder setNegativeButton(int negativeButtonText,
        DialogInterface.OnClickListener listener) {
      this.negativeButtonText = (String) context
          .getText(negativeButtonText);
      this.negativeButtonClickListener = listener;
      return this;
    }
    public Builder setNegativeButton(String negativeButtonText,
        DialogInterface.OnClickListener listener) {
      this.negativeButtonText = negativeButtonText;
      this.negativeButtonClickListener = listener;
      return this;
    }
    public CustomDialogPriceModify create() {
      LayoutInflater inflater = (LayoutInflater) context
          .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
      // instantiate the dialog with the custom Theme
      final CustomDialogPriceModify dialog = new CustomDialogPriceModify(
          context, R.style.Dialog);
      dialog.setCanceledOnTouchOutside(false);
      dialog.setCancelable(false);
      View layout = inflater.inflate(
          R.layout.activity_systemsettings_pricecustom_dialog, null);
      dialog.addContentView(layout, new LayoutParams(
          LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
      // set the dialog title
      ((TextView) layout.findViewById(R.id.title)).setText(title);
      priceText = (EditText) layout.findViewById(R.id.price);
      //对edittext进行初始化,关键代码
      if (positiveButtonText != null) {
        ((Button) layout.findViewById(R.id.positiveButton))
            .setText(positiveButtonText);
        if (positiveButtonClickListener != null) {
          ((Button) layout.findViewById(R.id.positiveButton))
              .setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  positiveButtonClickListener.onClick(dialog,
                      DialogInterface.BUTTON_POSITIVE);
                }
              });
        }
      } else {
        // if no confirm button just set the visibility to GONE
        layout.findViewById(R.id.positiveButton).setVisibility(
            View.GONE);
      }
      // set the cancel button
      if (negativeButtonText != null) {
        ((Button) layout.findViewById(R.id.negativeButton))
            .setText(negativeButtonText);
        if (negativeButtonClickListener != null) {
          ((Button) layout.findViewById(R.id.negativeButton))
              .setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  negativeButtonClickListener.onClick(dialog,
                      DialogInterface.BUTTON_NEGATIVE);
                }
              });
        }
      } else {
        // if no confirm button just set the visibility to GONE
        layout.findViewById(R.id.negativeButton).setVisibility(
            View.GONE);
      }
      // set the content message
      if (message != null) {
        TextView msgView = (TextView) layout.findViewById(R.id.message);
        msgView.setText(message);
        if (textSize != 0) {
          msgView.setTextSize(textSize);
        }
      } else if (contentView != null) {
      }
      dialog.setContentView(layout);
      return dialog;
    }
  }
}

3.剩下的就是布局代码,包括一些圆角的,如果需要的可以参考我之前的博文,就不贴代码了。完成效果如下:

总结一些,对于自定义的对话框,无法在主activity中初始化对话框里的控件的时候,可以将初始化或者取值的操作放到自定义控件里面,这样就可以取值和赋值操作,忙活了一天,终于在师傅的指导下完成了这部分功能,看来单纯的看网上的答案,可能我几天都解决不了,还得多了解一些本质,对象得传递,得好好恶补一下基础知识,不懂得或者需要解释的可以联系我。

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

(0)

相关推荐

  • ANDROID中自定义对话框AlertDialog使用示例

    在Android开发中,我们经常会需要在Android界面上弹出一些对话框,比如询问用户或者让用户选择.这些功能我们叫它Android Dialog对话框,AlertDialog实现方法为建造者模式.AlertDialog中定义的一些对话框往往无法满足我们关于对话框的需求,这时我们就需要通过自定义对话框VIEW来实现需求,这里我自定义一个登陆的提示对话框,效果图显示如下: Layout(alertdialog自定义登陆按钮)界面代码: <?xml version="1.0" en

  • Android常用的AlertDialog对话框及自定义对话框

    常用的Dialog有确认对话框,单选按钮对话框,多选按钮对话框,复选按钮对话框另外还有自定义的对话框 AlertDialog的常用方法 setTitle:为对话框设置标题 setMessage:为对话框设置内容 setIcon:为对话框设置图标 setItems设置对话框要显示的list setMultiChoiceItems:一般用于复选框显示 setSingleChoiceItem:,设置单选按钮 setNeutralButton:普通按钮 setPositiveButton:添加确定按钮

  • Android EditText自定义样式的方法

    本文实例讲述了Android EditText自定义样式的方法.分享给大家供大家参考,具体如下: 1.去掉边框 EditText的background属性设置为@null就搞定了:android:background="@null" style属性倒是可加可不加 附原文: @SlumberMachine, that's a great observation! But, it seems that there is more to making a TextView editable

  • Android控件系列之EditText使用方法

    学习目的: 1.掌握在Android中如何建立EditText2.掌握EditText的常用属性3.掌握EditText焦点的事件.按键的事件(监听器) 介绍: EditText是接受用户输入信息的最重要控件.通过前面课程的学习,您可能会猜到可以利用EditText.getText()获取它的文本,但真正的项目中,可能没那么简单,需要更多的限制,如文本长度限制,是否数字限制等等. 鉴于手机屏幕尺寸有限,您可能总想着如何节约控件.在每个用户需要填写内容的文本框的左边加上标题在PC上是一种优雅的方法

  • Android中自定义对话框(Dialog)的实例代码

    1.修改系统默认的Dialog样式(风格.主题) 2.自定义Dialog布局文件 3.可以自己封装一个类,继承自Dialog或者直接使用Dialog类来实现,为了方便以后重复使用,建议自己封装一个Dialog类 第一步: 我们知道Android定义个控件或View的样式都是通过定义其style来实现的,查看Android框架中的主题文件,在源码中的路径:/frameworks/base/core/res/res/values/themes.xml,我们可以看到,Android为Dialog定义了

  • Android 自定义对话框 showSetPwdDialog

    样式如下所示: 布局: layout dialog_set_pwd.xml <?xml version="." encoding="utf-"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height=&

  • Android自定义对话框Dialog的简单实现

    本文着重研究了自定义对话框,通过一下步骤即可清晰的理解原理,通过更改界面设置和style类型,可以应用在各种各样适合自己的App中. 首先来看一下效果图: 首先是activity的界面 点击了上述图片的按钮后,弹出对话框: 点击对话框的确定按钮: 点击对话框的取消按钮: 下面来说一下具体实现步骤: 第一步:设置Dialog的样式(一般项目都可以直接拿来用):style.xml中 <!--自定义Dialog背景全透明无边框theme--> <style name="MyDialo

  • Android使用setCustomTitle()方法自定义对话框标题

    Android有自带的对话框标题,但是不太美观,如果要给弹出的对话框设置一个自定义的标题,使用AlertDialog.Builder的setCustomTitle()方法. 运行效果如下,左边是点击第一个按钮,弹出Android系统自带的对话框(直接用setTitle()设置标题):右边是点击第二个按钮,首先inflate一个View,然后用setCustomTitle()方法把该View设置成对话框的标题. 定义一个对话框标题的title.xml文件: <?xml version="1.

  • Android 根据EditText搜索框ListView动态显示数据

    根据EditText搜索框ListView动态显示数据是根据需求来的,觉得这之中涉及的东西可能比较的有意思,所以动手来写一写,希望对大家有点帮助. 首先,我们来分析下整个过程: 1.建立一个layout,包含一个EditText搜索框和一个ListView 2.创建一个数据集mData,用于ListView的Adapter的创建 3.添加EditText的文本改变的监听器 4.利用notifyDataSetChanged()动态更新ListView 第一步:创建一个搜索框 这个还是比较容易的,这

  • Android中实现EditText圆角的方法

    一.在drawable下面添加xml文件rounded_editview.xml 复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle">    <solid andr

  • Android EditText常用属性功能汇总

    本文总结分析了Android EditText常用属性.分享给大家供大家参考,具体如下: android:hint="请输入数字!"//设置显示在空间上的提示信息 android:numeric="integer"//设置只能输入整数,如果是小数则是:decimal android:singleLine="true"//设置单行输入,一旦设置为true,则文字不会自动换行. android:password="true"//设

随机推荐