我正试图从adialogfragment
向目标fragment
发送一些数据,但它不起作用。
我已经编写了以下代码,但它是通过exception
编写的:
java.lang.NullPointerException: Attempt to invoke interface method 'void com.x.x.FragmentAlertDialog$Communicator.setI(java.lang.String)' on a null object reference
代码:
public class FragmentAlertDialog extends DialogFragment {
Communicator callback;
public interface Communicator {
void setI(String name);
}
public static FragmentAlertDialog newInstance(String id, int title, int items) {
FragmentAlertDialog frag = new FragmentAlertDialog();
Bundle args = new Bundle();
args.putString("id", id);
args.putInt("title", title);
args.putInt("items", items);
frag.setArguments(args);
return frag;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callback = (Communicator) getTargetFragment();
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String id = getArguments().getString("id");
int title = getArguments().getInt("title");
String[] items = getResources().getStringArray(getArguments().getInt("items"));
switch (id) {
case MainActivity.DIALOG_1:
return new AlertDialog.Builder(getActivity())
.setTitle(title)
.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
callback.setI("Important Data");
}
}).create();
}
return null;
}
碎片类
public class FragmentXYXY extends Fragment implements View.OnClickListener, FragmentAlertDialog.Communicator {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.et_i:
DialogFragment newFragment = FragmentAlertDialog.newInstance(MainActivity.DIALOG_I, R.string.i_select, R.array.i_array);
newFragment.setTargetFragment(this, 0);
newFragment.show(getFragmentManager(), "dialog");
}
}
@Override
public void setI(String name) {
textI.setText(name);
}
有人能帮忙吗?
谢谢你
代码修改-newfragment.setTargetFragment(this,0);
最佳答案
你必须打电话setTargetFragment
setTargetFragment(this, 0);
为了获得
FragmentXYXY
中的参考。@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.et_i:
DialogFragment newFragment = FragmentAlertDialog.newInstance(MainActivity.DIALOG_I, R.string.i_select, R.array.i_array);
newFragment.setTargetFragment(this, 0);
newFragment.show(getFragmentManager(), "dialog");
}
}