本文出处:http://superonion.iteye.com/blog/1418467
我们知道,从一个Activity向另一个Activity传递数据,用Intent实现。而当一个浮在Activity之上的Dialog需要向该Activity传递数据时,应该怎么实现呢?接着上一篇文章:用Dialog创建带箭头的对话框。
现在PopupDialog中声明一个内部接口PriorityListener,接口中声明一个回调函数refreshPriorityUI,用于在Dialog的监听事件触发后刷新Activity的UI显示。然后在MainActivity中的Button点击事件中实现这个接口并将其作为PopupDialog的构造函数的参数传入,并实现refreshPriorityUI()方法。话不多说,直接上代码——
PopupDialog代码:
- public class PopupDialog extends Dialog {
- /**
- * 自定义Dialog监听器
- */
- public interface PriorityListener {
- /**
- * 回调函数,用于在Dialog的监听事件触发后刷新Activity的UI显示
- */
- public void refreshPriorityUI(String string);
- }
- private PriorityListener listener;
- /**
- * 带监听器参数的构造函数
- */
- public PopupDialog(Context context, int theme, PriorityListener listener) {
- super(context, theme);
- this.listener = listener;
- }
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.popup_dialog);
- Button buttonUp = (Button) findViewById(R.id.btn_up);
- buttonUp.setOnClickListener(new Button.OnClickListener() {
- @Override
- public void onClick(View v) {
- dismiss();
- listener.refreshPriorityUI("数据来自:上");
- }
- });
- }
- }
MainActivity代码:
- public class MainActivity extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Button button = (Button)findViewById(R.id.btn);
- button.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- PopupDialog popupDialog = new PopupDialog(MainActivity.this, R.style.dialog, new PopupDialog.PriorityListener() {
- @Override
- public void refreshPriorityUI(String string) {
- Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
- }
- });
- popupDialog.setCanceledOnTouchOutside(true); // 点击Dialog之外的区域对话框消失
- Window window = popupDialog.getWindow();
- WindowManager.LayoutParams lp = window.getAttributes();
- lp.y = -64; // 设置竖直方向的偏移量
- lp.dimAmount = 0f; // 弹出对话框的时候背景不变暗
- popupDialog.show();
- }
- });
- }
- }
最后效果:
点击“上”之后,MainActivity会调用refreshPriorityUI()方法: