公众号同名
#Android回调机制之Activity与DialogFragment数据传递
在实际编程过程中,我们经常碰到这样一种情况:
在新建的Dialog
或者Fragment
中修改数据,但是要在Activity
或其他位置进行数据更新,那怎么处理呢?此时我们的回调机制就派上了用场。
那么什么是回调机制呢,回调机制是一种依赖于接口的传递机制,旨在为其他类暴漏方法以使得其他类具备获取数据权限(PS:这里的权限指的是修饰词引起的访问权限)。说这么多,估计大多数人还是一头雾水,接下来,让我们写一个Demo实践一下吧。
我们在新建的项目中新建CustomDialogFragment
类,继承自DialogFragment
并重写基本构造方法,代码如下:
public class CustomDialogFragment extends DialogFragment {
public CustomDialogFragment() {
super();
}
}
接着创建CustomDialogFragment
的布局文件,并重写其onCreateView()
方法加载自定义布局。
布局文件如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:layout_width="match_parent"
android:layout_height="64dp"
android:background="#FFFFBB33"
android:contentDescription="@string/app_name"
android:scaleType="center"
/>
<EditText
android:id="@+id/id_txt_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"