将结果从活动传递到片段

时间:2013-11-11 06:59:41

标签: android android-fragments

我有两项活动(A和B)。活动A由片段F组成。如何将活动B的结果传递给我的片段F?这是我的代码:

片段F

public class FragmentF extends Fragment implements OnCLickListener {

// my editText is in this fragmentf layout
EditText editText;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragmentf, container, false);            
        Button b = (Button) v.findViewById(R.id.to_actb);
        b.setOnClickListener(this); 
        return v;
    }

    @Override
    public void onClick(View v) {

        Intent intent = new Intent(getActivity(), ActivityB.class);
        startActivityForResult(intent, 1);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, intent);

          if (requestCode == 1) {

             if(resultCode == ActivityB.RESULT_OK){      
                 String hey = getActivity().getIntent().getStringExtra("hey.hello.MESSAGE");
                 EditText editText = (EditText) getActivity().findViewById(R.id.text1);
                 editText.setText(hey); 
             }
          }
    }
}

活动B

public class ActivityB extends Activity {

    public final static String EXTRA_MESSAGE = "hey.hello.MESSAGE";

....

    public void to_acta(View view) {

        Intent intent = new Intent(this, ActivityA.class);
        TextView textView = (TextView) findViewById(R.id.text);
        String message = textView.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        setResult(RESULT_OK,intent);
        finish();      
    }

我的问题是,当我点击" to_acta"按钮,我的编辑文本中没有添加任何内容" text1"。

1 个答案:

答案 0 :(得分:-2)

替换

String hey = getActivity().getIntent().getStringExtra("hey.hello.MESSAGE");

String hey = data.getStringExtra(ActivityB.EXTRA_MESSAGE);