1. 程式人生 > >android 如何在自定義對話方塊中獲取edittext中的資料

android 如何在自定義對話方塊中獲取edittext中的資料

在專案中忽然遇到這樣的問題,需要自定義對話方塊,對話方塊需要有一個輸入框,以便修改所選中的價格,然後點選確定之後,修改所顯示的價格。遇到的最大的問題就是如何能夠獲取到自定義對話方塊當中edittext輸入的數值,百度了很久,看到的答案都是如下:

//得到自定義對話方塊
  final View DialogView = a .inflate ( R.layout.loand, null);
這是關鍵的程式碼</span></strong></span>
 
 //建立對話方塊
        
        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 
[email protected]
  * @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) { <span style="font-size:24px;color:#ff0000;"><strong> // 獲取edittext的值 String priceStr = builder.getPrice();//關鍵程式碼,getPrice放在自定義的alertdialog類裡面,進行初始化</strong></span> 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;
		}
<span style="font-size:24px;color:#ff0000;"><strong>         //關鍵程式碼
		public String getPrice() {
			return priceText.getText().toString();
		}</strong></span>

		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
			<span style="font-size:24px;color:#ff0000;"><strong>((TextView) layout.findViewById(R.id.title)).setText(title);
			priceText = (EditText) layout.findViewById(R.id.price);
			//對edittext進行初始化,關鍵程式碼</strong></span>
			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中初始化對話方塊裡的控制元件的時候,可以將初始化或者取值的操作放到自定義控制元件裡面,這樣就可以取值和賦值操作,忙活了一天,終於在師傅的指導下完成了這部分功能,看來單純的看網上的答案,可能我幾天都解決不了,還得多瞭解一些本質,物件得傳遞,得好好惡補一下基礎知識,不懂得或者需要解釋的可以聯絡我。