我正在将我的对话框转换为DialogFragments
. 我正在按照此处的说明进行操作,但看起来他们正在使用它,Activity
而我正在使用它Fragment
。我已经创建了Listener
片段的背面,但是当我调用getActivity()
它时,它会抛出一个NullPointerException
:
public class DialogTextAdd extends DialogFragment implements OnEditorActionListener {
private EditText mText;
public interface DialogTextAddListener {
void onDialogTextAdd(final String inputText);
}
public DialogTextAdd() {
// Empty constructor required for DialogFragment
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.dialog_edit, container);
mText = (EditText)view.findViewById(R.id.Text_add);
getDialog().setTitle("Add Text");
// Show soft keyboard automatically
mText.requestFocus();
getDialog().getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
mText.setOnEditorActionListener(this);
return view;
}
@Override
public boolean onEditorAction(final TextView v, final int actionId, final KeyEvent event) {
if (EditorInfo.IME_ACTION_DONE == actionId) {
new MyFragment().onDialogTextAdd(mText.getText().toString()); //think this is my problem
this.dismiss();
return true;
}
return false;
}
}
public class MyFragment extends SherlockListFragment implements DialogKeywordAddListener
{
@Override
public void onDialogTextAdd(final String text) {
Toast.makeText(getActivity(), text + " saved", Toast.LENGTH_SHORT).show();
}
@Override
public void onAttach(Activity act) {
super.onAttach(act);
}
}
使用此代码使其工作:
MyFragment mf = new MyFragment();
Bundle args = new Bundle();
args.putString("text", mText.getText().toString());
mf.setArguments(args);
getActivity().getSupportFragmentManager().beginTransaction().add(mf, "my_fragment").commit();