Android自定义dialog向Activity传递数据

自定义对话框:

 

package org.lee.android;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class InputDialog extends Dialog {
	private Context context;
	private EditText editText;
	private Button button_sure;
	private Button button_cancel;
	public OnSureClickListener mListener;

	public InputDialog(Context context) {
		super(context);
		this.context = context;
	}

	public InputDialog(Context context, OnSureClickListener listener) {
		super(context);
		mListener = listener;
	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.project_edit_dialog);
		setView();
	}

	private void setView() {
		button_sure = (Button) findViewById(R.id.button_project_dialog_sure);
		button_cancel = (Button) findViewById(R.id.button_project_dialog_cancel);
		editText = (EditText) findViewById(R.id.edit_project_new_name);
		// 这里的监听事件,因为该类继承lDialog类的DialogInterface,而DialogInterface中也有OnClickListener,因此需要用到全名View.OnClickListener
		button_sure.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mListener.getText(editText.getText().toString());
				dismiss();
			}
		});
		button_cancel.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				mListener.getText(editText.getText().toString());// 在Button监听事件中实现这一方法
				dismiss();
			}
		});
	}

	public interface OnSureClickListener {
		void getText(String string); // 声明获取EditText中数据的接口
	}
	
}

 

 

 

 

 

Activity中调用方法:

 

OnClickListener click_new = new OnClickListener() {
		public void onClick(View v) {
			OnSureClickListener listener1 = new OnSureClickListener() {
				public void getText(String string) {
					inputFile = string;
					try {
						addFile();
					} catch (IOException e) {
					}
				}
			};
			InputDialog d1 = new InputDialog(ProjectActivity.this, listener1);
			d1.show();
		}
   
    };

 

 

你可能感兴趣的:(Android进阶)