如何将数据从活动发送到Fragment Activity?

时间:2014-03-10 12:44:42

标签: android android-fragments

我在这个问题上引用了很多代码,但是对我的问题没有任何帮助。 这是我想要将数据发送到上一个FragmentActivity的代码:

public class AddTask extends Activity {

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_task);

    ImageButton position = (ImageButton) findViewById(R.id.select_position);

    position.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent m = new Intent().setClass(getApplicationContext(),
                    MapActivity.class);
            startActivity(m);

        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_add_task, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.accept:
        FinishActivity();
        finish();
        break;
    case R.id.cancle:
        finish();
        break;
    }
    return super.onOptionsItemSelected(item);
}

protected void FinishActivity() {
    EditText activity = (EditText) findViewById(R.id.activity_name);
    EditText description = (EditText) findViewById(R.id.description);
    EditText address = (EditText) findViewById(R.id.address);

    Bundle bundle = new Bundle();
    bundle.putString("activity", activity.getText().toString());
    if (activity.toString().isEmpty() || description.toString().isEmpty()
            || address.toString().isEmpty()) {

        Toast.makeText(this, "Field must not be empty", Toast.LENGTH_LONG)
                .show();
    }
}
}

任何人都可以告诉我在此代码中使用什么来发送数据,我已使用Fragment类发送它,但它在Activity中出错。

1 个答案:

答案 0 :(得分:0)

Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:



 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        String strtext = getArguments().getString("edttext");    
        return inflater.inflate(R.layout.fragment, container, false);
    }