我知道有类似的问题,但我找不到一个答案来解决我的问题。
我有一个DialogUpdateEmail,我想从ProfileFragment打开它。在对话框中,我想输入我的新电子邮件,并将其发送到我的ProfileFragment,以便在数据库中也更改它。
ProfileFragment.java :
import androidx.fragment.app.Fragment;
public class ProfileFragment extends Fragment implements SendInputEmail {
public static final int PROFILE_FRAGMENT = 1;
private static final String TAG = "ProfileFragment";
private TextView TVHello, TVUsernameMessage, TVusernameinfo, TVemailinfo, TVbirthdate;
public void sendInput(String input) {
Log.d(TAG, "sendInput: found incoming input: " + input);
TVemailinfo.setText(input);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
Button Bsignout = (Button) v.findViewById(R.id.signoutbutton);
Button Beditusername = (Button) v.findViewById(R.id.editusernamebutton);
Button Beditemail = (Button) v.findViewById(R.id.editemailbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: opening email dialog");
DialogUpdateEmail dialog = new DialogUpdateEmail();
dialog.setTargetFragment(ProfileFragment.this,PROFILE_FRAGMENT);
dialog.show(getActivity().getFragmentManager(), "DialogUpdateEmail");
}
});
return v;
}
DialogUpdateEmail.java :
public class DialogUpdateEmail extends DialogFragment implements SendInputEmail {
private static final String TAG = "DialogUpdateEmail";
SendInputEmail mHost = (SendInputEmail)getTargetFragment();
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.popup, container, false);
EditText UpdateEmail = (EditText) view.findViewById(R.id.emailinfoupdate);
Button Beditemail = (Button) view.findViewById(R.id.updatesavebutton);
Button Bcancelemail = (Button) view.findViewById(R.id.updatecancelbutton);
Beditemail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: capturing input.");
String input = UpdateEmail.getText().toString();
Log.d(TAG, "input : "+input);
mHost.sendInput(input);
getDialog().dismiss();
}
});
return view ;
}
public void onAttach(Context context) {
super.onAttach(context);
try{
mHost = (SendInputEmail) getTargetFragment();
}catch (ClassCastException e){
Log.e(TAG, "onAttach: ClassCastException : " + e.getMessage() );
}
}
@Override
public void sendInput(String input) {
}
}
发送输入电子邮件接口:
public interface SendInputEmail {
void sendInput(String input);
}
我的问题是,当我尝试在ProfileFragment中使用setTargetFragment时,出现了一个错误。它说Profile Fragment不是一个Fragment,我真的不知道为什么。
第一次
1条答案
按热度按时间t2a7ltrp1#
来自here中的文档:
我们使用observer/listener模式将电子邮件从对话框发送到片段。
在你的
ProfileFragment
中实现DialogEditListener
并订阅它来监听对话框中的点击按钮,如下所示: