有問題越來越片段到活動通信正常工作..麻煩與片段TextWatcher到活動通信
我有一個片段編輯框,我需要它給每個編輯後的值發送回主要活動。
片段類:
public class FragA extends Fragment {
FragAInt mCallback;
public interface FragAInt{
public void onEditBoxEdited(String boxContent);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_a, container, false);
final View et = view.findViewById(R.id.eboxa) ;
((EditText) et).addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
mCallback.onEditBoxEdited(((EditText) et).getText().toString());
}
});
return view;
}
}
MainActivity
public class MainActivity extends FragmentActivity implements FragA.FragAInt{
private String editBoxVal;
public void onEditBoxEdited(String editBoxContent){
this.editBoxVal= editBoxContent;
}
}
該應用程序將運行,但它會只要你在一個空指針異常退出框中鍵入崩潰。
我哪裏出錯了?
完整的錯誤:
java.lang.NullPointerException:
Attempt to invoke interface method 'void nemo.myapplication.FragA$FragAInt.onEditBoxEdited(java.lang.String)' on a null object reference
at nemo.myapplication.FragA$1.afterTextChanged(FragA.java:49)
at android.widget.TextView.sendAfterTextChanged(TextView.java:8017)
at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:10182)
at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:1043)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:560)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:492)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:34)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:685)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:445)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:340)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:78)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
添加您有的錯誤。我想獲取對EditText視圖的引用是空的。並且你正試圖調用它的方法。 mCallback未初始化,請檢查這一個。 – Rafal
這就是你所有的代碼?你在哪裏分配mCallback變量?你如何將片段添加到活動中? – diedu
這就是我所有的代碼。進入這個例子:https://developer.android.com/training/basics/fragments/communicating.html 我確實有onAttach函數,但它抱怨函數已被棄用。 –