1
我有兩個片段。片段A和片段B.片段A具有稱爲EmpID的EditText視圖。片段B有一個名爲「提交」的按鈕。當我點擊片段B提交按鈕,我想找回我試圖做到這一點使用下面的代碼片段中的A.進入的EmpID的價值,在OnClickListener的按鈕:獲取不同片段的EditText值
EditText empID = (EditText) getView().findViewById(R.id.EmpID);
String empIDStr = empID.getText().toString(); //I get null here
但我即使輸入數據,也要保持空值。我不能從另一個片段獲得EditText視圖的值嗎?我確定我在這裏錯過了一些東西。任何幫助,將不勝感激。謝謝。
Here's the logcat output:
01-23 12:32:13.883: E/AndroidRuntime(1171): FATAL EXCEPTION: main
01-23 12:32:13.883: E/AndroidRuntime(1171): java.lang.NullPointerException
01-23 12:32:13.883: E/AndroidRuntime(1171): at ex.testApp.FragmentB$1.onClick(FragmentB.java:85)
01-23 12:32:13.883: E/AndroidRuntime(1171): at android.view.View.performClick(View.java:3110)
01-23 12:32:13.883: E/AndroidRuntime(1171): at android.view.View$PerformClick.run(View.java:11928)
01-23 12:32:13.883: E/AndroidRuntime(1171): at android.os.Handler.handleCallback(Handler.java:587)
01-23 12:32:13.883: E/AndroidRuntime(1171): at android.os.Handler.dispatchMessage(Handler.java:92)
01-23 12:32:13.883: E/AndroidRuntime(1171): at android.os.Looper.loop(Looper.java:132)
01-23 12:32:13.883: E/AndroidRuntime(1171): at android.app.ActivityThread.main(ActivityThread.java:4025)
01-23 12:32:13.883: E/AndroidRuntime(1171): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 12:32:13.883: E/AndroidRuntime(1171): at java.lang.reflect.Method.invoke(Method.java:491)
01-23 12:32:13.883: E/AndroidRuntime(1171): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
01-23 12:32:13.883: E/AndroidRuntime(1171): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
01-23 12:32:13.883: E/AndroidRuntime(1171): at dalvik.system.NativeStart.main(Native Method)
這裏的FragmentB.java:
public class FragmentB extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.FragmentB, container, false);
}
@Override
public void onStart() {
super.onStart();
final Button btnLeft = (Button) getActivity().findViewById(R.id.btnLeft);
final Button btnRight = (Button) getActivity().findViewById(R.id.btnRight);
buttonClick(btnLeft, btnRight);
}
private void buttonClick(final Button btnLeft, final Button btnRight) {
btnLeft.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (btnLeft.getText().equals("Submit")) {
EditText empID = (EditText) getView().findViewById(R.id.EmpID);
String empIDStr = empID.getText().toString(); //I get null here
.....
logcat會幫助我們更多。 – prolink007
我們是否也可以看到FragmentB.java? – prolink007
它是getActivity()。不在 中的getView()EditText empID =(EditText)getActivity()。findViewById(R.id.EmpID); 謝謝你的時間。 – user1005585