Analysis:Fragment和Activity的通信
Resolution:fragment定义回调接口,activity实现具体方法
Steps:
In fragment:
1. fragment中定义接口并确保activity调用了这个接口
2. 调用接口方法传值给activity
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener{ OnDateSetListener mListener; @Override // 2. onAttach() detect whether the Activity has inherited the interface, // if not it will throw an exception // Called when a fragment is first attached to its context public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnDateSetListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnDateSetListener"); } } @RequiresApi(api = Build.VERSION_CODES.N) @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { // Do something with the date chosen by the user // 3. call method in interface to send values mListener.onDateSet(year, month, day); } // 1. Define a callback interface public interface OnDateSetListener{ // method to be implemented in activity void onDateSet(int year, int month, int day); } }
In Activity:
1. 调用接口
2. 实现接口方法(使用接收到的变量显示在textview)
// implement interface[DatePickerFragment.OnDateSetListener] declared in fragment public class RegisterActivity extends AppCompatActivity implements DatePickerFragment.OnDateSetListener { private TextView tv_showDoB; private TextView tv_login; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); tv_showDoB = (TextView) findViewById(R.id.tv_showDoB); tv_login = (TextView) findViewById(R.id.tv_login); tv_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(RegisterActivity.this, MainActivity.class); //start intent startActivity(intent); finish(); } }); } public void showDatePickerDialog(View v) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getFragmentManager() , "datePicker"); } // 4. Implement method in interface public void onDateSet(int year, int month, int day) { tv_showDoB.setText(year+"-"+(++month)+"-"+day); } }
效果: