从不同的片段获取EditText值

时间:2012-01-23 18:52:43

标签: android android-edittext fragment

我有两个片段。片段A和片段B.片段A具有名为EmpID的EditText视图。片段B有一个名为“提交”的按钮。当我单击片段B中的“提交”按钮时,我想检索在片段A中的EmpID中输入的值。我正在尝试使用以下代码执行此操作,在按钮的OnClickListener中:

    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
.....

1 个答案:

答案 0 :(得分:2)

我只是将变量设置为静态并且有效。

private static EditText empID;